Changing the response object from OWIN Middleware

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

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

    public override async Task Invoke(OwinRequest request, OwinResponse response)
    {
        var header = request.GetHeader("X-Whatever-Header");

        await Next.Invoke(request, response);

        response.SetHeader("X-MyResponse-Header", "Some Value");
        response.StatusCode = 403;

    }
}

Questions:

  1. Is it the recommended practice to derive from OwinMiddleware? I see that in Katana source, some of the middleware classes derive from OwinMiddleware and some do not.

  2. I can see the request headers okay. Setting response header or status code after Next.Invoke in my middleware has no effect on the response returned to the client. But if I set the response header or status before the Next.Invoke call, the response with headers and the status that I set is returned to the client. What is the right way of setting these?

  1. Yes, deriving from OwinMiddleware is recommended. The reason some middleware classes don't derive from OwinMiddleware is that either they haven't switched over yet because the class was introduced recently. Or to avoid having the assembly take a dependency on the Microsoft.Owin assembly for some reason.

  2. The probable reason setting stuff on the response after calling Invoke on Next doesn't work is that the response HTTP header gets sent as soon as anyone starts writing to the response body stream. So any changes to status code or HTTP headers after a middleware component starts writing to the response body won't have any effect.

What you can try doing is to use the OnSendingHeaders callback that OWIN provides. Here's how you can use it:

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";
    }, response);

  var header = request.Headers["X-Whatever-Header"];

  await Next.Invoke(context);
}

Credit to biscuit314 for updating my answer.

Changing the response object from OWIN Middleware, My OWIN middleware is like this. (Framework is ASP.NET Web API). public class MyMiddleware : OwinMiddleware; {; public MyMiddleware(OwinMiddleware� Setting response header or status code after Next.Invoke in my middleware has no effect on the response returned to the client. But if I set the response header or status before the Next.Invoke call, the response with headers and the status that I set is returned to the client.

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);
}

Replace response body using owin middleware - asp.net - html, Replace response body using owin middleware - asp.net. Here's my request headers: Request Url: http://internalserver:8181/citations Request Method: GET� Changing the response object from OWIN Middleware (2) . My OWIN middleware is like this. (Framework is ASP.NET Web API).

I used this code to get the time taken by every request.

appBuilder.Use(async (context, next) =>
        {
            var watch = new Stopwatch();
            watch.Start();
            await next();
            watch.Stop();
            context.Response.Headers.Set("ResponseTime", watch.Elapsed.Seconds.ToString());
        });

Owin component : Modifying owin response - mitzen, public class CustomerCifCleaner : OwinMiddleware hold a reference to what will be the outbound/processed response stream object. How can I safely intercept the Response stream in a custom Owin Middleware (1) I do not think you will need a sub-classed stream but then here is how you can read the response. Just ensure this middleware is the first one in the OWIN pipeline so that it will be the last one to inspect the response.

Creating OWIN Middleware using Microsoft Katana, Step by step walkthrough for creating OWIN/Katana middleware using the If you try modifying the response headers after writing to the� In Owin/Katana the response body (and, of course, the headers) are sent to the client at the precise moment when a middleware calls Write on the Response object of the IOwinContext. This means that if your next middleware is writing the response body your client will receive it before your server-side code returns from the call to await Next

Using ASP.NET Core's middleware to modify response body, 0, `FrameResponseStream` (https://github.com/aspnet/K is the stream-object on `context.Response.Body`. In v2.1-preview, it's been changed to� Change OWIN Request.Body in middleware. Ask Question so it can be deserialized to object and later passed as an argument for Controller method. Here's what I do

Note: the issue referenced in this post has been fixed and will get released with ASP.NET Core 1.1.0. While creating a small piece of middleware to modify the response body's content, I had trouble getting anything to appear in my browser.

Comments
  • Thanks Youssef. For point #2, is there an example code in Katana source or somewhere else that I can look at, from the best practice pt of view? I believe, what I'm asking for is a fairly common need and is every one supposed to do this stream switching just to set a response header, if we use OWIN middleware? Any pointers will be appreciated.
  • I'm able to resolve the problem by following your suggestion but isn't there an easy way out? I mean this is too much of work to just set a response header on the way out, especially if one is used to Web API's message handler.
  • Updated the answer with a simpler method. Please let me know if it works.
  • "Yes, deriving from OwinMiddleware is recommended." No, no it is not. github.com/owin/owin/issues/20 github.com/owin/owin/issues/19
  • @Valipour, the OnSendingHeaders callback only runs once data starts being sent on the wire, so you should be able to inspect the response at that point