【发布时间】:2018-01-12 14:23:22
【问题描述】:
我有一些 ASP.NET Core MVC 中间件来捕获我想从中返回响应的未处理异常。
虽然httpContext.Response.WriteAsync 很容易写一个字符串,例如使用JsonSerializer 将对象序列化为字符串,我想使用标准的序列化设置和内容协商,以便如果我将默认输出格式更改为XML 或text/xml 在我有多个输出格式化程序时发送接受标头如果我从控制器返回 ObjectResult,则会返回 XML。
有谁知道如何在中间件中实现这一点?
这是我目前只写 JSON 的代码:
public class UnhandledExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IOutputFormatter _outputFormatter;
private readonly IHttpResponseStreamWriterFactory _streamWriterFactory;
public UnhandledExceptionMiddleware(RequestDelegate next, JsonOutputFormatter outputFormatter, IHttpResponseStreamWriterFactory streamWriterFactory)
{
_next = next;
_outputFormatter = outputFormatter;
_streamWriterFactory = streamWriterFactory;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var error = new ErrorResultModel("Internal Server Error", exception.Message, exception.StackTrace);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await _outputFormatter.WriteAsync(new OutputFormatterWriteContext(context, _streamWriterFactory.CreateWriter, typeof(ErrorResultModel), error));
}
}
其中ErrorResultModel 定义为:
public class ErrorResultModel
{
public string ResultMessage { get; };
public string ExceptionMessage { get; };
public string ExceptionStackTrace { get; };
public ErrorResultModel(string resultMessage, string exceptionMessage, string exceptionStackTrace)
{
ResultMessage = resultMessage;
ExceptionMessage = exceptionMessage;
ExceptionStackTrace = exceptionStackTrace;
}
}
【问题讨论】:
标签: .net-core asp.net-core-mvc middleware asp.net-core-2.0