我有一个简单的中间件:
public class MiddlewareInterceptor
{
RequestDelegate _next;
public MiddlewareInterceptor(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext ctx)
{
ctx.Response.WriteAsync("<h2>From SomeMiddleWare</h2>");
return _next(ctx);
}
}
在我的Startup.cs配置方法中,我这样挂钩:
app.UseMiddleware<MiddlewareInterceptor>();
以上版本和应用程序似乎运行正常,但我在拦截器Invoke方法中的断点永远不会发生。同样,从来没有任何产出。我也尝试了Debug.WriteLine
。
现在,我也尝试过这种方法:
public class MiddlewareInterceptor : OwinMiddleware
{
public MiddlewareInterceptor(OwinMiddleware next) : base(next){}
public override async Task Invoke(IOwinContext context)
{
Debug.WriteLine(context.Request.Uri.ToString());
await Next.Invoke(context);
}
}
在我的Startup.cs配置方法中,我这样挂钩:
app.Use(next => new MiddlewareInterceptor(next).Invoke);
不幸的是,基础OwinMiddleware
构造函数正在寻找下一个OwinMiddleware
作为参数,这与您的RequestDelegate
不同。因此app.Use
我的MiddlewareInterceptor
实例化失败,因为next
的类型为RequestDelegate
。
最后,我在Configure方法中直接尝试了一个内联函数,它也永远不会遇到断点:
app.Use(async (ctx, next) =>
{
System.Diagnostics.Debug.WriteLine("Hello");
await next();
});
就目前而言,似乎我无法使用OWIN制作基本的中间件拦截器。我错过了什么?
答案 0 :(得分:5)
上述中间件在管道中的顺序是什么?确保在任何终止管道请求部分之前执行此操作;例如。 UseMvc();