Basic programming, .NET technology.

3. Asp.net core - fundamentals - Middleware

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.


Part 1: Startup file.

Part 2: Dependency Injection.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.

This part is to summarise some knowledge concerning the Middleware in Asp .net core.

a. What is middleware
  • Middleware is software added to the pipeline to process requests and responses.
  • When a request comes, it goes through one by one middleware (you can think that all middleware do the common process for each request, response)
  • To use middleware in IApplicationBuilder, use:
    • Run: param: context
    • Use: param: context, next -> to invoke next middleware
    • Map: to branch middleware
  • We have some built-in middleware, we can use them in configure method.
  • Of course, we can also create custom middleware.
b. Order of middleware



--> Endpoint middleware to turn the request into an action method in the controller.



c. How to create a custom middleware
  • step 1: Encapsulate custom middleware in class
    • Convention: {Name}Middleware
    • Include:
      • a constructor with parameter type is "ContextDelegate".
      • A public method is named Invoke or InvokeAsync. This method must:
    • For example:
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
// IMyScopedService is injected into Invoke
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
svc.MyProperty = 1000;
await _next(httpContext);
}
}

  • step 2: create a middleware extension method through IApplicationBuilder:
    • Name convention: Use{MiddlewareName}
using Microsoft.AspNetCore.Builder;
namespace Culture
{
public static class RequestCultureMiddlewareExtensions
{
public static IApplicationBuilder UseRequestCulture(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestCultureMiddleware>();
}
}
}

  • step 3: Call middleware in Configure method
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseRequestCulture();
app.Run(async (context) =>
{
await context.Response.WriteAsync(
$"Hello {CultureInfo.CurrentCulture.DisplayName}");
});
}
}


References:

Share:

0 nhận xét:

Đăng nhận xét

Featured Posts

Data type 3 - string type