文章目录
一、Use
代码如下(示例):
app.Use(async (ctx, next) =>
{
//await ctx.Response.WriteAsync("Hello");
await next();
if (ctx.Response.HasStarted)
{
await ctx.Response.WriteAsync("一旦已经开始输出,则不能再修改响应头的内容");
}
await ctx.Response.WriteAsync("hello2");
});
二、Map
代码如下(示例):
app.Map("/xyz", appBuilder =>
{
appBuilder.Use(async (ctx, next) =>
{
//await ctx.Response.WriteAsync("Hello");
await next();
await ctx.Response.WriteAsync("Hello21");
});
});
三、MapWhen
代码如下(示例):
app.MapWhen(ctx =>
{
return !ctx.Request.Query.Keys.Contains("xyz");
}, appBuilder =>
{
appBuilder.Run(async ctx =>
{
await ctx.Response.WriteAsync("new xyz");
});
});
四、Run终极者中间件
代码如下(示例):
app.Run(async ctx => {
await ctx.Response.WriteAsync("run done!");
});
五、自定义中间件
1.定义自定义中间件类
代码如下(示例):
public class CustomMiddleware
{
RequestDelegate _next;
ILogger _logger;
public CustomMiddleware(RequestDelegate next, ILogger<CustomMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext ctx)
{
using (_logger.BeginScope("traceId:{traceId}", ctx.TraceIdentifier))
{
_logger.LogDebug("Starting");
await _next(ctx);
_logger.LogDebug("End");
}
}
}
注意:一定要写InvokeAsync或Invoke方法
2.定义UseCustomMiddleware扩展方法
代码如下(示例):
public static class CustomBuilderExtensions
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomMiddleware>();
}
}
3.在Configure配置自定义中间件的扩展方法
代码如下(示例):
app.UseCustomMiddleware();