ASP. NET Core development-Middleware (Middleware), coremiddleware
Reference page:
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-layout.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-view-start.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-import-view.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-taghelpers.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-edit-form.html
ASP. NET Core development, development and use of Middleware (Middleware ).
Middleware is a software component assembled into an application pipeline to process requests and responses.
Each component selects whether to pass the request to the next component in the pipeline, and can perform specific operations after the previous and next components are called in the pipeline.
Details
Development Middleware (Middleware)
Today, we will implement a middleware that records ip addresses.
1. Create an asp.net core project and select an empty template.
Then add a Microsoft. Extensions. Logging. Console for the project.
NuGet command line, please use official source.
Install-Package Microsoft. Extensions. Logging. Console-Pre
2. Create a new class: RequestIPMiddleware. cs
public class RequestIPMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) { _next = next; _logger = loggerFactory.CreateLogger<RequestIPMiddleware>(); } public async Task Invoke(HttpContext context) { _logger.LogInformation("User IP: " + context.Connection.RemoteIpAddress.ToString()); await _next.Invoke(context); } }
3. Create another: RequestIPExtensions. cs
public static class RequestIPExtensions { public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestIPMiddleware>(); } }
In this way, we have compiled a middleware.
Use Middleware (Middleware)
1. Use
Add app. UseRequestIP () in Startup. cs ()
Public void Configure (IApplicationBuilder app, ILoggerFactory loggerfactory) {loggerfactory. addConsole (minLevel: LogLevel. information); app. useRequestIP (); // use the middleware app. run (async (context) =>{ await context. response. writeAsync ("Hello World! ");});}
Then run the program. I chose to use Kestrel.
Access: http: // localhost: 5000/
Run successfully.
We can further improve this middleware to add more features, such as restricted access.
If you think this article is helpful to you, click"Recommendation", Thank you.