Dogodek
Power BI DataViz Svetovno prvenstvo
14. feb., 16h - 31. mar., 16h
S 4 možnosti za vstop, bi lahko zmagal konferenčni paket in da bi bilo v ŽIVO Grand Finale v Las Vegasu
Več informacijTa brskalnik ni več podprt.
Izvedite nadgradnjo na Microsoft Edge, če želite izkoristiti vse prednosti najnovejših funkcij, varnostnih posodobitev in tehnične podpore.
Opomba
This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.
Opozorilo
This version of ASP.NET Core is no longer supported. For more information, see the .NET and .NET Core Support Policy. For the current release, see the .NET 9 version of this article.
Pomembno
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 9 version of this article.
IMiddlewareFactory/IMiddleware is an extensibility point for middleware activation that offers the following benefits:
UseMiddleware extension methods check if a middleware's registered type implements IMiddleware. If it does, the IMiddlewareFactory instance registered in the container is used to resolve the IMiddleware implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container.
IMiddleware is activated per client request (connection), so scoped services can be injected into the middleware's constructor.
IMiddleware defines middleware for the app's request pipeline. The InvokeAsync(HttpContext, RequestDelegate) method handles requests and returns a Task that represents the execution of the middleware.
Middleware activated by convention:
public class ConventionalMiddleware
{
private readonly RequestDelegate _next;
public ConventionalMiddleware(RequestDelegate next)
=> _next = next;
public async Task InvokeAsync(HttpContext context, SampleDbContext dbContext)
{
var keyValue = context.Request.Query["key"];
if (!string.IsNullOrWhiteSpace(keyValue))
{
dbContext.Requests.Add(new Request("Conventional", keyValue));
await dbContext.SaveChangesAsync();
}
await _next(context);
}
}
Middleware activated by MiddlewareFactory:
public class FactoryActivatedMiddleware : IMiddleware
{
private readonly SampleDbContext _dbContext;
public FactoryActivatedMiddleware(SampleDbContext dbContext)
=> _dbContext = dbContext;
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var keyValue = context.Request.Query["key"];
if (!string.IsNullOrWhiteSpace(keyValue))
{
_dbContext.Requests.Add(new Request("Factory", keyValue));
await _dbContext.SaveChangesAsync();
}
await next(context);
}
}
Extensions are created for the middleware:
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseConventionalMiddleware(
this IApplicationBuilder app)
=> app.UseMiddleware<ConventionalMiddleware>();
public static IApplicationBuilder UseFactoryActivatedMiddleware(
this IApplicationBuilder app)
=> app.UseMiddleware<FactoryActivatedMiddleware>();
}
It isn't possible to pass objects to the factory-activated middleware with UseMiddleware:
public static IApplicationBuilder UseFactoryActivatedMiddleware(
this IApplicationBuilder app, bool option)
{
// Passing 'option' as an argument throws a NotSupportedException at runtime.
return app.UseMiddleware<FactoryActivatedMiddleware>(option);
}
The factory-activated middleware is added to the built-in container in Program.cs
:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<SampleDbContext>
(options => options.UseInMemoryDatabase("SampleDb"));
builder.Services.AddTransient<FactoryActivatedMiddleware>();
Both middleware are registered in the request processing pipeline, also in Program.cs
:
var app = builder.Build();
app.UseConventionalMiddleware();
app.UseFactoryActivatedMiddleware();
IMiddlewareFactory provides methods to create middleware. The middleware factory implementation is registered in the container as a scoped service.
The default IMiddlewareFactory implementation, MiddlewareFactory, is found in the Microsoft.AspNetCore.Http package.
IMiddlewareFactory/IMiddleware is an extensibility point for middleware activation.
UseMiddleware extension methods check if a middleware's registered type implements IMiddleware. If it does, the IMiddlewareFactory instance registered in the container is used to resolve the IMiddleware implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container.
Benefits:
IMiddleware is activated per client request (connection), so scoped services can be injected into the middleware's constructor.
View or download sample code (how to download)
IMiddleware defines middleware for the app's request pipeline. The InvokeAsync(HttpContext, RequestDelegate) method handles requests and returns a Task that represents the execution of the middleware.
Middleware activated by convention:
public class ConventionalMiddleware
{
private readonly RequestDelegate _next;
public ConventionalMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, AppDbContext db)
{
var keyValue = context.Request.Query["key"];
if (!string.IsNullOrWhiteSpace(keyValue))
{
db.Add(new Request()
{
DT = DateTime.UtcNow,
MiddlewareActivation = "ConventionalMiddleware",
Value = keyValue
});
await db.SaveChangesAsync();
}
await _next(context);
}
}
Middleware activated by MiddlewareFactory:
public class FactoryActivatedMiddleware : IMiddleware
{
private readonly AppDbContext _db;
public FactoryActivatedMiddleware(AppDbContext db)
{
_db = db;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var keyValue = context.Request.Query["key"];
if (!string.IsNullOrWhiteSpace(keyValue))
{
_db.Add(new Request()
{
DT = DateTime.UtcNow,
MiddlewareActivation = "FactoryActivatedMiddleware",
Value = keyValue
});
await _db.SaveChangesAsync();
}
await next(context);
}
}
Extensions are created for the middleware:
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseConventionalMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<ConventionalMiddleware>();
}
public static IApplicationBuilder UseFactoryActivatedMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<FactoryActivatedMiddleware>();
}
}
It isn't possible to pass objects to the factory-activated middleware with UseMiddleware:
public static IApplicationBuilder UseFactoryActivatedMiddleware(
this IApplicationBuilder builder, bool option)
{
// Passing 'option' as an argument throws a NotSupportedException at runtime.
return builder.UseMiddleware<FactoryActivatedMiddleware>(option);
}
The factory-activated middleware is added to the built-in container in Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("InMemoryDb"));
services.AddTransient<FactoryActivatedMiddleware>();
services.AddRazorPages();
}
Both middleware are registered in the request processing pipeline in Startup.Configure
:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseConventionalMiddleware();
app.UseFactoryActivatedMiddleware();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
IMiddlewareFactory provides methods to create middleware. The middleware factory implementation is registered in the container as a scoped service.
The default IMiddlewareFactory implementation, MiddlewareFactory, is found in the Microsoft.AspNetCore.Http package.
IMiddlewareFactory/IMiddleware is an extensibility point for middleware activation.
UseMiddleware extension methods check if a middleware's registered type implements IMiddleware. If it does, the IMiddlewareFactory instance registered in the container is used to resolve the IMiddleware implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container.
Benefits:
IMiddleware is activated per client request (connection), so scoped services can be injected into the middleware's constructor.
View or download sample code (how to download)
IMiddleware defines middleware for the app's request pipeline. The InvokeAsync(HttpContext, RequestDelegate) method handles requests and returns a Task that represents the execution of the middleware.
Middleware activated by convention:
public class ConventionalMiddleware
{
private readonly RequestDelegate _next;
public ConventionalMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, AppDbContext db)
{
var keyValue = context.Request.Query["key"];
if (!string.IsNullOrWhiteSpace(keyValue))
{
db.Add(new Request()
{
DT = DateTime.UtcNow,
MiddlewareActivation = "ConventionalMiddleware",
Value = keyValue
});
await db.SaveChangesAsync();
}
await _next(context);
}
}
Middleware activated by MiddlewareFactory:
public class FactoryActivatedMiddleware : IMiddleware
{
private readonly AppDbContext _db;
public FactoryActivatedMiddleware(AppDbContext db)
{
_db = db;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var keyValue = context.Request.Query["key"];
if (!string.IsNullOrWhiteSpace(keyValue))
{
_db.Add(new Request()
{
DT = DateTime.UtcNow,
MiddlewareActivation = "FactoryActivatedMiddleware",
Value = keyValue
});
await _db.SaveChangesAsync();
}
await next(context);
}
}
Extensions are created for the middleware:
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseConventionalMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<ConventionalMiddleware>();
}
public static IApplicationBuilder UseFactoryActivatedMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<FactoryActivatedMiddleware>();
}
}
It isn't possible to pass objects to the factory-activated middleware with UseMiddleware:
public static IApplicationBuilder UseFactoryActivatedMiddleware(
this IApplicationBuilder builder, bool option)
{
// Passing 'option' as an argument throws a NotSupportedException at runtime.
return builder.UseMiddleware<FactoryActivatedMiddleware>(option);
}
The factory-activated middleware is added to the built-in container in Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("InMemoryDb"));
services.AddTransient<FactoryActivatedMiddleware>();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Both middleware are registered in the request processing pipeline in Startup.Configure
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseConventionalMiddleware();
app.UseFactoryActivatedMiddleware();
app.UseStaticFiles();
app.UseMvc();
}
IMiddlewareFactory provides methods to create middleware. The middleware factory implementation is registered in the container as a scoped service.
The default IMiddlewareFactory implementation, MiddlewareFactory, is found in the Microsoft.AspNetCore.Http package.
Povratne informacije o izdelku ASP.NET Core
ASP.NET Core je odprtokodni projekt. Izberite povezavo za pošiljanje povratnih informacij:
Dogodek
Power BI DataViz Svetovno prvenstvo
14. feb., 16h - 31. mar., 16h
S 4 možnosti za vstop, bi lahko zmagal konferenčni paket in da bi bilo v ŽIVO Grand Finale v Las Vegasu
Več informacijUsposabljanje
Modul
Customize ASP.NET Core behavior with middleware - Training
Understand and implement middleware in an ASP.NET Core app. Use included middleware like HTTP logging and authentication. Create custom middleware to handle requests and responses.
Dokumentacija
Write custom ASP.NET Core middleware
Learn how to write custom ASP.NET Core middleware.
Middleware activation with a third-party container in ASP.NET Core
Learn how to use strongly-typed middleware with factory-based activation and a third-party container in ASP.NET Core.
Request and Response operations in ASP.NET Core
Learn how to read the request body and write the response body in ASP.NET Core.
Learn about ASP.NET Core middleware and the request pipeline.