9

ASP.NET Core 5 Route to Code: Taking advantage of Microsoft.AspNetCore.Http json...

 3 years ago
source link: https://anthonygiretti.com/2020/09/29/asp-net-core-5-route-to-code-taking-advantage-of-microsoft-aspnetcore-http-json-extensions/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
route-to-code-json-extensions.png?fit=750%2C386&ssl=1

ASP.NET Core 5 Route to Code: Taking advantage of Microsoft.AspNetCore.Http json extensions

2020-09-29 by anthonygiretti

Introduction

A while ago, I have introduced a cool feature of ASP.NET Core: how to build a lightweight API without using a framework. I named it like this: Nano service with ASP.NET Core: which you can find here: https://anthonygiretti.com/2020/06/29/nano-services-with-asp-net-core-or-how -to-build-a-light-api, I still like this feature and Microsoft called it: Route to Code, how could I not have thought about it before?
In this article I will tell you about an improvement made by ASP.NET Core 5: a simpler writing of Route to Code services thanks to JSON extensions for HttpRequest and HttpResponse based on System.Text.Json brought by ASP. NET Core 3 in 2019.

How to play with HttpRequest and HttpResponse before and with ASP.NET Core 5

Let’s consider two scenarii: implementing GET & POST endpoints with ASP. NET Core 3 with its new JSON library System.Text.Json. The GET endpoint will return a list of countries and the POST endpoint will create a country. In both cases we need to deal with JSON data, with GET want to serialize the list of country in the HttpResponse and in the POST endpoint we want to deserialize the JSON data from the HttpRequest:

using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Text.Json; using aspnetcore_api_lite.Services; using System.Net; using aspnetcore_api_lite.Models; using System.IO;

namespace aspnetcore_api_lite { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddScoped<CountryService>(); }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }

app.UseRouting();

app.UseEndpoints(endpoints => { endpoints.MapGet("/countries", async context => { var countryService = context.Request.HttpContext.RequestServices.GetRequiredService<CountryService>();

var countries = await countryService.Get(); var response = JsonSerializer.Serialize(countries);

await context.Response.WriteAsync(response); });

endpoints.MapPost("/countries", async context => { var countryService = context.Request.HttpContext.RequestServices.GetRequiredService<CountryService>(); string bodyText = string.Empty;

using (StreamReader reader = new StreamReader(context.Request.Body)) { bodyText = await reader.ReadToEndAsync(); }

var country = JsonSerializer.Deserialize<Country>(bodyText); var countries = await countryService.Create(country);

context.Response.StatusCode = (int)HttpStatusCode.Created; }); }); } } }

As you can see the implementation is very simple, you just have to call the classical JSON serialization / deserialization methods aka JsonSerializer.Serialize() and JsonSerializer.Deserialize<T>(). Note that you also need to read the request body with a StreamReader to convert it into text like this:

using (StreamReader reader = new StreamReader(context.Request.Body))
{
   bodyText = await reader.ReadToEndAsync();
}

What if I tell you with ASP.NET Core 5 this job is very simpler ? 😉

ASP.NET Core 5 includes a built-in assembly that contains new JSON extensions based on System.Text.Json for HttpRequest and HttpResponse. That means you don’t need to download any Nuget package, it’s a part of ASP.NET Core:

httprequest-json-extensions-1024x296.png?resize=640%2C185&ssl=1
httpresponse-json-extensions-1024x272.png?resize=640%2C170&ssl=1

So now how can we rewrite our Route to Code services ? like this:

using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using aspnetcore_api_lite.Services; using System.Net; using aspnetcore_api_lite.Models;

namespace aspnetcore_api_lite { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddScoped<CountryService>(); }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }

app.UseRouting();

app.UseEndpoints(endpoints => { endpoints.MapGet("/countries", async context => { var countryService = context.Request.HttpContext.RequestServices.GetRequiredService<CountryService>(); var countries = await countryService.Get();

await context.Response.WriteAsJsonAsync(countries); });

endpoints.MapPost("/countries", async context => { var countryService = context.Request.HttpContext.RequestServices.GetRequiredService<CountryService>();

if (context.Request.HasJsonContentType()) { var country = await context.Request.ReadFromJsonAsync<Country>(); var countries = await countryService.Create(country);

context.Response.StatusCode = (int)HttpStatusCode.Created; } else { context.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType; } }); }); } } }

As you can see, the code is now much simpler. Another great feature: HasJsonContentType() extension on the HttpRequest object. This method allows to know if the content received is in JSON or not, and you are now able to handle it, for example, you can return the status HttpStatusCode.UnsupportedMediaType if you don’t received an expected JSON payload is you request body. Practical isn’t it ? 🙂

Conclusion

Route to Code is a great feature of ASP.NET Core. This feature is evolving in ASP.NET Core 5 and it’s great. I strongly suggest you to learn more about this feature I’m sure you’ll like too. If you are interested you can watch this interesting video on Channel 9:

Enjoy 🙂

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK