Rewrite the answer in Owin middleware

In my OWIN application, I register middleware to intercept the results of other environments in the pipeline, and if the condition is met, I need to reverse the response from being (maybe 302

or 200

) to 403

(forbidden).

There is, of course, not a very clean way, namely to manually clear all headers, content type, etc. and set statusCode to 403

, but that doesn't seem right to me.

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 rewriting the response 200

(when it hits the line where we set it StatusCode

, it jumps out and dumps the response).

I am new to OWIN and I may not understand how it works.

Is there any other way to do this?

+3


source to share


2 answers


Here's what I found.

If you try to change the response headers after you reach the controller, the headers may have already been sent.

This is why you must subscribe to OnSendingHeaders(Action<object> callback, object state)

before proceeding with the pipeline.



Example:

...
context.Response.OnSendingHeaders(obj => { /* Do stuff */ }, new object());
// Then call the next middleware
await this.Next.Invoke(context);
...

      

+2


source


You should only call Next.Invoke if someCondition (context) is false. I think you will find this blog post .



0


source







All Articles