简体   繁体   中英

Owin context.Response.Body always empty

have followed through some samples and creating a new buffer MemoryStream to replace the Response.Body before calling next().

Below is my middleware :

public class TrackingMiddleware
{
    private readonly AppFunc next;

    public TrackingMiddleware(AppFunc next)
    {
        this.next = next;
    }

    public async Task Invoke(IDictionary<string, object> env)
    {
        IOwinContext context = new OwinContext(env);

        // Buffer the response
        var stream = context.Response.Body;
        var buffer = new MemoryStream();
        context.Response.Body = buffer;

        await this.next(env);

        buffer.Seek(0, SeekOrigin.Begin);
        var reader = new StreamReader(buffer);
        string responseBody = await reader.ReadToEndAsync();

        buffer.Seek(0, SeekOrigin.Begin);
        await buffer.CopyToAsync(stream);
    }
}

the responsBody is always empty, event my ApiController's Action returned List of data.

Below is my Owin Startup class (Did i miss out anything ? )

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    static Startup()
    {
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new OAuthAppProvider(),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
            AllowInsecureHttp = true
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);

        app.Use<TrackingMiddleware>();
    }
}

Below is my ApiController

public class TestController : ApiController
{

    public IHttpActionResult Get()
    {
        return Json(new string[] {"123", "asdfsdf"});
    }
}

and My Web api configuration is registered through Global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
{

    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

Is this the reason that messed up the sequence of the middleware?

Alternatively, if i use MVC method and it works with the HttpContext.Current.Response by referencing following sample

You have to put the original stream back into the response

context.Response.Body = stream;

That way it can be read by the previous middleware in the pipeline

You would also want to dispose of any resources that are no longer needed

public async Task Invoke(IDictionary<string, object> env) {
    IOwinContext context = new OwinContext(env);

    // Buffer the response
    var stream = context.Response.Body;
    using (var buffer = new MemoryStream()) {
        context.Response.Body = buffer;

        //call next in pipeline
        await this.next(env);

        //reset the original response body
        context.Response.Body = stream;

        //get data from buffer
        buffer.Seek(0, SeekOrigin.Begin);
        var reader = new StreamReader(buffer);
        string responseBody = await reader.ReadToEndAsync();    
        buffer.Seek(0, SeekOrigin.Begin);

        //put data into original stream to continue the flow.
        await buffer.CopyToAsync(stream);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM