Middleware (middleware)
ASP. NET core development, development and use of middleware (middleware).
Middleware is a software component that is assembled into an application pipeline to process requests and responses.
Each component chooses whether to pass a request to the next component in the pipeline and can perform a specific operation before and after the next component is called in the pipeline.
Specific
Development Middleware (middleware)
Today we will implement a middleware that records IP.
1. Create a new ASP. NET Core project and select an empty template.
Then add a Microsoft.Extensions.Logging.Console to the project
NuGet command line, please use the 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 one: RequestIPExtensions.cs
public static class Requestipextensions {public static Iapplicationbuilder Userequestip (this Iapplicationbuilder builder) { return builder. Usemiddleware<requestipmiddleware> (); } }
So we've written a middleware.
Using Middleware (middleware)
1. Use
Add apps to Startup.cs. Userequestip ()
public void Configure (Iapplicationbuilder app, Iloggerfactory loggerfactory) { loggerfactory. Addconsole (minLevel:LogLevel.Information); App. Userequestip ();//Use middleware app. Run (Async (context) = { await context. Response.writeasync ("Hello world!");} );
Then run the program and I choose to use Kestrel.
Visit: Http://localhost:5000/
Run successfully.
Here we can further improve the middleware, add more features, such as restricted access.
Middleware (middleware)