声明自定义中间件及处理方法
public class RequestSetOptionsMiddleware { /// <summary> /// 可以处理HTTP请求的函数 /// </summary> private readonly RequestDelegate _next; public RequestSetOptionsMiddleware(RequestDelegate next) { _next = next; } /// <summary> /// 执行当前自定义中间件的处理 /// 注意自定义中间件名字必须为Invoke或者InvokeAsync /// </summary> /// <param name="httpcontext"></param> /// <returns></returns> public async Task Invoke(HttpContext httpcontext) { //获取httpcontext请求中的option参数 var option = httpcontext.Request.Query["option"]; if (!string.IsNullOrWhiteSpace(option)) { httpcontext.Items["option"] = WebUtility.HtmlEncode(option); } await _next(httpcontext); } }
/// <summary> /// 继承IStartupFilter接口 /// </summary> public class RequestSetOptionsStartupFilter : IStartupFilter { /// <summary> /// 构造配置 /// </summary> /// <param name="next"></param> /// <returns></returns> public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return builder => { //引用自定义中间件 builder.UseMiddleware<RequestSetOptionsMiddleware>(); //管道继续运行 next(builder); }; } }
在Startup.cs引用自定义中间件:
public void ConfigureServices(IServiceCollection services) { services.AddTransient<IStartupFilter, RequestSetOptionsStartupFilter>(); }
实现效果如下:
模拟请求
自定义中间件获取httpcontext并进行相应的处理