Created
October 23, 2017 17:19
-
-
Save JacopoMangiavacchi/30a186662b46033a6c1c9deb642f349b to your computer and use it in GitHub Desktop.
C# - .Net Core Rest Test : <- Post <- Request <- Get
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Text; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.AspNetCore.Routing; | |
using Newtonsoft.Json; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
namespace csharptest | |
{ | |
class Language | |
{ | |
public string language { get; set; } | |
} | |
class Request | |
{ | |
public string url { get; set; } | |
} | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var host = new WebHostBuilder() | |
.UseKestrel() | |
.UseStartup<Startup>() | |
.UseUrls("http://localhost:8030") | |
.Build(); | |
host.Run(); | |
} | |
} | |
class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddRouting(); | |
} | |
public void Configure(IApplicationBuilder app) | |
{ | |
var routeBuilder = new RouteBuilder(app); | |
routeBuilder.MapGet("language", context => { | |
Language language = new Language(); | |
language.language = "C#"; | |
string response = JsonConvert.SerializeObject(language); | |
//string response = JsonConvert.SerializeObject(new { language = "C#" }); | |
return context.Response.WriteAsync(response); | |
}); | |
routeBuilder.MapPost("request", async (context) => { | |
string bodyAsString; | |
using (var streamReader = new StreamReader(context.Request.Body, Encoding.UTF8)) | |
{ | |
bodyAsString = streamReader.ReadToEnd(); | |
} | |
Request request = JsonConvert.DeserializeObject<Request>(bodyAsString); | |
var client = new HttpClient(); | |
var stringTask = client.GetStringAsync(request.url); | |
var languageText = await stringTask; | |
await context.Response.WriteAsync(languageText); | |
//unmarshal from data to json and marshal again from json to data | |
// var language = JsonConvert.DeserializeObject(languageText); | |
// string responseText = JsonConvert.SerializeObject(language); | |
// await context.Response.WriteAsync(responseText); | |
return; | |
}); | |
var routes = routeBuilder.Build(); | |
app.UseRouter(routes); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment