Changing the response object from OWIN Middleware

后端 未结 3 1652
一向
一向 2020-12-25 12:49

My OWIN middleware is like this. (Framework is ASP.NET Web API).

public class MyMiddleware : OwinMiddleware
{
    public MyMiddleware(OwinMiddleware next) :          


        
3条回答
  •  伪装坚强ぢ
    2020-12-25 12:58

    I tried to edit Youssef's excellent answer to correct a minor bug and update the example with how the OwinMiddleware now works.

    The edit was rejected (well, approved by one, rejected by one for being too minor, and rejected by two for being too major).

    Here is that version of Youssef's code:

    public override async Task Invoke(IOwinContext context)
    {
      var response = context.Response;
      var request =  context.Request;
    
      response.OnSendingHeaders(state =>
        {
            var resp = (OwinResponse)state;
            resp.Headers.Add("X-MyResponse-Header", "Some Value");
            resp.StatusCode = 403;
            resp.ReasonPhrase = "Forbidden"; // if you're going to change the status code
                                             // you probably should also change the reason phrase
        }, response);
    
      var header = request.Headers["X-Whatever-Header"];
    
      await Next.Invoke(context);
    }
    

提交回复
热议问题