在Owin中间件中覆盖响应主体

问题描述 投票:0回答:1

我有一个我正在使用的Owin中间件类。目的是在检测到401,403或405 HTTP状态代码时覆盖响应正文,并用JSON对象替换正文。到目前为止这是我的方法:

public override async Task Invoke(IOwinContext context)
        {
            await Next.Invoke(context);

            if (context.Response.StatusCode == 401 || context.Response.StatusCode == 403 || context.Response.StatusCode == 405)
            {

                var owinResponse = context.Response;
                var owinResponseStream = owinResponse.Body;
                var responseBuffer = new MemoryStream();
                owinResponse.Body = responseBuffer;

                string message;

                switch (context.Response.StatusCode)
                {
                    case 401:
                        message = "unauthorized request";
                        break;
                    case 403:
                        message = "forbidden request";
                        break;
                    default:
                        message = "request not allowed";
                        break;
                }
                var newResponse = new ResponseMessage<string>
                {
                    IsError = true,
                    StatusCode = (HttpStatusCode) Enum.Parse(typeof(HttpStatusCode), context.Response.StatusCode.ToString()),
                    Data = null,
                    Message = message
                };

                var customResponseBody = new StringContent(JsonConvert.SerializeObject(newResponse));
                var customResponseStream = await customResponseBody.ReadAsStreamAsync();
                await customResponseStream.CopyToAsync(owinResponseStream);
                owinResponse.ContentType = "application/json";
                owinResponse.ContentLength = customResponseStream.Length;
                owinResponse.StatusCode = 200;
                owinResponse.Body = owinResponseStream;
            }

        }

在大多数情况下它是有效的,但是响应主体被附加到而不是被替换。例如,在401错误的情况下,响应正文是:

{"message":"Authorization has been denied for this request."}
{"IsError":true,"StatusCode":401,"Data":null,"Message":"unauthorized request"}

代替:

{"IsError":true,"StatusCode":401,"Data":null,"Message":"unauthorized request"}

我确信这与我写回响应机构的方式有关,但到目前为止还没有解决问题。

任何建议将不胜感激。

谢谢

c# asp.net-web-api owin
1个回答
0
投票

当您首先将响应主体设置为内存流时,光标(当前位置)将移动到它的末尾。 owinResponse.Body = responseBuffer;,结果,我们得到了{"message":"Authorization has been denied for this request."}stored并且光标指向最后。

再次,在您的方法结束时,您编写新的响应owinResponse.Body = owinResponseStream;,其中包含消息{"IsError":true,"StatusCode":401,"Data":null,"Message":"unauthorized request"}

由于当前位置指向流的末尾,因此它将附加。

尝试删除第一组身体 owinResponse.Body = responseBuffer; 因为您不需要原始响应消息。

© www.soinside.com 2019 - 2024. All rights reserved.