[英]Rewrite the response in Owin Middleware
In my OWIN app, I register a middleware to intercept the outcome of other middlewares down in the pipeline and if a condition is met, I need to totally change the response from whatever it is (could be 302
or 200
) to 403
(forbidden). 在我的OWIN应用程序中,我注册了一个中间件来拦截管道中其他中间件的结果,如果条件满足,我需要完全改变响应(无论是
302
或200
)到403
(禁止) 。
There is ofcourse a not-very-clean-way and that is to manually clear all the headers, content type, etc. and set the statusCode to 403
but this feels to me a wrong approach. 有一个不太干净的方法,那就是手动清除所有标题,内容类型等,并将statusCode设置为
403
但这对我来说是错误的方法。
public override async Task Invoke(IOwinContext context)
{
await this.Next.Invoke(context);
if (someCondition(context))
{
var headers = context.Response.Headers;
headers.Keys.ForEach(k => headers.Remove(k));
context.Response.StatusCode = 403;
context.Response.ContentType = string.Empty;
context.Response.ContentLength = null;
await context.Response.WriteAsync(string.Empty);
}
}
Plus the fact that this approach doesn't work when overwriting a 200
response (when it hits the line where we set StatusCode
, it jumps out and flushes the response). 此外,这种方法在覆盖
200
响应时不起作用(当它到达我们设置StatusCode
的行时,它会跳出并刷新响应)。
I'm new to OWIN and I may be misunderstanding the way it works. 我是OWIN的新手,我可能误解了它的工作方式。
Is there any other way you would do this? 你还有其他办法吗?
Here is what I discovered. 这是我发现的。
If you try to change the response headers after you reached the controller, the headers might already have been sent. 如果在到达控制器后尝试更改响应标头,则可能已经发送了标头。
That's why you should subscribe to the OnSendingHeaders(Action<object> callback, object state)
before continuing the pipeline. 这就是为什么你应该在继续管道之前订阅
OnSendingHeaders(Action<object> callback, object state)
。
Example: 例:
...
context.Response.OnSendingHeaders(obj => { /* Do stuff */ }, new object());
// Then call the next middleware
await this.Next.Invoke(context);
...
You should call Next.Invoke only if someCondition(context) is false. 仅当someCondition(context)为false时,才应调用Next.Invoke。 I think you'll find this blog post helpful.
我想你会发现这篇博文有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.