Wie kann ich wieder eine Antwort in ASP.NET Kern MVC-middleware unter Verwendung von MVC ist die content-negotiation?

Habe ich einige ASP.NET Kern MVC-middleware zu fangen, nicht behandelte Ausnahmen, die ich gerne wieder eine Reaktion aus.

Weile ist es einfach nur httpContext.Response.WriteAsync zu schreiben, die einen string und z.B. JsonSerializer zu serialise ein Objekt in einen string, würde ich gerne die standard-serialisieren, Einstellungen und content negotiation, so dass wenn ich meine Standard-Ausgabe-Formatierung für XML-oder eine text/xml accept-header gesendet wird, wenn ich mehrere output formatter konfiguriert, dann wird XML zurückgegeben, wie es tut, wenn ich wieder ein ObjectResult aus einem controller.

Weiß jemand wie das erreicht werden kann, in der middleware?

Hier ist mein code bisher, die schreibt nur 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));
    }
}

wo ErrorResultModel ist definiert als:

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;
    }
}
InformationsquelleAutor Joseph Earl | 2018-01-12
Schreibe einen Kommentar