【发布时间】:2019-04-03 16:29:20
【问题描述】:
使用 .NET Core、C#。
我在启动时添加了中间件,因此我可以格式化错误响应
public async Task Invoke(HttpContext context)
{
var body = context.Response.Body;
using (var newBody= new MemoryStream())
{
context.Response.Body = newBody;
await _next(context);
if (context.Response.StatusCode != 200 && context.Response.StatusCode != 206)
{
context.Response.Body = body;
updatedBody.Seek(0, SeekOrigin.Begin);
var msg= new StreamReader(updatedBody).ReadToEnd();
if (msg.Length > 0) {
context.Response.ContentType = _messageParser.GetFormat();
var response = _messageParser.MakeItPretty(msg);
await context.Response.WriteAsync(response);
}
}
}
}
【问题讨论】:
-
当 StatusCode 不是 200 也不是 206 时,您缺少 ELSE。
-
@jdweng 这应该是一个答案
标签: c# .net-core asp.net-core-mvc middleware