包装所有回复

use*_*173 5 c# asp.net-core-mvc asp.net-core asp.net5

我想包装所有的http响应.
例如,我们有一个返回一些JSON数据的动作:

public IActionResult Get() 
{
    var res = new
        {
            MessageBody = "Test",
            SomeData = 1
        };

        return Ok(res);
}
Run Code Online (Sandbox Code Playgroud)

我希望我的回答如下:

{    
    "StatusCode":200,
    "Result":
    {
        "MessageBody ":"Test",
        "SomeData":1        
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有错误,则响应必须包含响应中的ErrorMessage字段.

在mvc 5中我使用过DelegationHandler,但是在asp.net核心中这个类没有实现.现在,我们必须使用中间件.

这是mvc 5的代码:

public class WrappingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        return BuildApiResponse(request, response);
    }

    private static HttpResponseMessage BuildApiResponse(HttpRequestMessage request, HttpResponseMessage response)
    {
        object content;
        string errorMessage = null;

        if (response.TryGetContentValue(out content) && !response.IsSuccessStatusCode)
        {
            HttpError error = content as HttpError;

            if (error != null)
            {
                content = null;
                errorMessage = error.Message;

#if DEBUG
                errorMessage = string.Concat(errorMessage, error.ExceptionMessage, error.StackTrace);
#endif
            }
        }

        var newResponse = request.CreateResponse(response.StatusCode, new ApiResponse(response.StatusCode, content, errorMessage));

        foreach (var header in response.Headers)
        {
            newResponse.Headers.Add(header.Key, header.Value);
        }

        return newResponse;
    }
}
Run Code Online (Sandbox Code Playgroud)

而且,asp.net核心的中间件.没有TryGetContentValue,HttpError并且在asp.net核心其他的东西.所以,我想首先阅读回复正文:

 public class FormatApiResponseMiddleware
 {
        private readonly RequestDelegate _next;

        public FormatApiResponseMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        private bool IsSuccessStatusCode(int statusCode)
        {
            return (statusCode >= 200) && (statusCode <= 299);

        }

        public async Task Invoke(HttpContext context)
        {
            object content = null;
            string errorMessage = null;

            if (!IsSuccessStatusCode(context.Response.StatusCode))
            {
                content = null;
                //how to get error 
            }

            var body= context.Response.Body;
        }
}
Run Code Online (Sandbox Code Playgroud)

但是,Body流有CanRead相同的false,我得到错误,无法读取流.如何正确包装回复?

Set*_*Set 0

我建议使用ExceptionHandlerMiddleware作为关于如何实现中间件的模板/示例。

\n\n

例如,当响应已经开始时,您应该注意这种情况

\n\n
// We can\'t do anything if the response has already started, just abort.\nif (context.Response.HasStarted)\n{\n    _logger.LogWarning("The response has already started, the error handler will not be executed.");\n    throw;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者如果您想替换它,请不要忘记清除当前响应:

\n\n
context.Response.Clear();\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

此外,也许您会发现重用它并实现您自己的错误处理程序而不是完整的中间件很有用。这样您就可以向客户端发送自定义 JSON 错误。为此,定义一个代表您的自定义错误的类:

\n\n
public class ErrorDto\n{\n   public int Code { get; set; }\n   public string Message { get; set; }\n\n   // other fields\n\n   public override string ToString()\n   {\n      return JsonConvert.SerializeObject(this);\n   }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后在方法中注册一个异常处理中间件Configure。注意中间件的注册顺序,确保\xe2\x80\x99s先于MVC注册,例如:

\n\n
app.UseExceptionHandler(errorApp =>\n{\n    errorApp.Run(async context =>\n    {\n        context.Response.StatusCode = 500; // or another Status\n        context.Response.ContentType = "application/json";\n\n        var error = context.Features.Get<IExceptionHandlerFeature>();\n        if (error != null)\n        {\n            var ex = error.Error;\n\n            await context.Response.WriteAsync(new ErrorDto()\n            {\n                Code = 1, //<your custom code based on Exception Type>,\n                Message = ex.Message // or your custom message\n                // \xe2\x80\xa6 other custom data\n            }.ToString(), Encoding.UTF8);\n        }\n    });\n});\n
Run Code Online (Sandbox Code Playgroud)\n