簡體   English   中英

中間件處理后的響應主體不變

[英]Response body unchanged after being processed by middleware

我試圖編寫一個調用下一​​個中間件的中間件,然后無論該中間件的響應主體是什么,它將由我的中間件進行更改。

這是Startup類中的Configuration()方法的樣子:

public void Configuration(IAppBuilder app)
{
    app.Use<OAuthAuthenticationFailCustomResponse>();
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}


這是我寫的中間件:

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

    public async override Task Invoke(IOwinContext context)
    {
        var stream = context.Response.Body;

        using (var buffer = new MemoryStream())
        {
            context.Response.Body = buffer;

            await Next.Invoke(context);

            buffer.Seek(0, SeekOrigin.Begin);

            var byteArray = Encoding.ASCII.GetBytes("Hello World");
            context.Response.StatusCode = 200;
            context.Response.ContentLength = byteArray.Length;

            buffer.SetLength(0);
            buffer.Write(byteArray, 0, byteArray.Length);
            buffer.Seek(0, SeekOrigin.Begin);
            buffer.CopyTo(stream);
        }
    }
}


但是,調用API后,我仍然收到OAuthBearerAuthentication中間件的響應,即:

{“ Message”:“此請求已被拒絕授權。” }


是我學習編寫更改響應正文的代碼的地方。

原始流未放回上下文響應主體

public async override Task Invoke(IOwinContext context) {
    // hold a reference to what will be the outbound/processed response stream object 
    var stream = context.Response.Body;

    // create a stream that will be sent to the response stream before processing
    using (var buffer = new MemoryStream()) {
         // set the response stream to the buffer to hold the unaltered response
        context.Response.Body = buffer;

        // allow other middleware to respond
        await Next.Invoke(context);

        // we have the unaltered response, go to start
        buffer.Seek(0, SeekOrigin.Begin);

        // read the stream from the buffer
        var reader = new StreamReader(buffer);
        string responseBody = reader.ReadToEnd();

        //...decide what you want to do with the responseBody from other middleware

        //custom response
        var byteArray = Encoding.ASCII.GetBytes("Hello World");

        //write custom response to stream
        stream.Write(byteArray, 0, byteArray.Length);

        //reset the response body back to the original stream
        context.Response.Body = stream;
        context.Response.StatusCode = 200;
        context.Response.ContentLength = byteArray.Length;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM