As known, IApplicationBuilder of the method Configure (class Startup) in ASP.NET Core requires specific semantics (to have method 'Invoke' with input parameter of HttpContext type and Task as return value). But why it's not implemented as interface? I can write something like it:
public class FakeMiddleware
{
}
and register it:
app.UseMiddleware<FakeMiddleware>();
and we'll get an runtime error. Of course, it's trivial thing and easy to be found and fix, but it's implemented so rough, without interface?
Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions.
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.
Middleware only has access to the HttpContext and anything added by preceding middleware. In contrast, filters have access to the wider MVC context, so can access routing data and model binding information for example.
Run() will end the request, and app. Use() will pass the request to next middleware.
The Invoke method is flexible and you can ask for additional parameters. ASP.NET will inject the additional parameters using the application's service configuration.
public async Task Invoke(HttpContext ctx,
IHostingEnvironment host,
ISomethingElse service)
{
// ...
}
C# interface definitions can't provide this flexibility in a nice way.
Since AspNetCore2.0 you can set middleware which implements interface IMiddleware.
public class InterfaceMiddleware : IMiddleware
{
private InterfaceMiddlewareOptions _opts;
public InterfaceMiddleware(IOptions<InterfaceMiddlewareOptions> opts)
{
_opts = opts.Value;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await context.Response.WriteAsync(_opts.Message);
}
}
In addition to app.UseMiddleware<InterfaceMiddleware>()
. You need to register your middleware in DI(singleton lifetime is not required).
public void ConfigureServices(IServiceCollection services)
{
services.Configure<InterfaceMiddlewareOptions>(opts =>
{
opts.Message = "IMiddleware interface is implemented";
});
services.AddSingleton<InterfaceMiddleware>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With