ASP.Net Core 2.0-如何从中间件返回自定义json或xml响应?

phi*_*-fx 3 request-pipeline asp.net-core asp.net-core-middleware asp.net-core-2.0

在ASP.Net Core 2.0中,我试图返回带有状态代码的格式化为json或xml的消息。我从控制器返回自定义消息没有问题,但是我不知道如何在中间件中处理它。

到目前为止,我的中间件类如下所示:

public class HeaderValidation
{
    private readonly RequestDelegate _next;
    public HeaderValidation(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        // How to return a json or xml formatted custom message with a http status code?

        await _next.Invoke(httpContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

Set*_*Set 12

要在中间件中填写响应,请使用httpContext.Response返回HttpResponse此请求的对象的属性。以下代码显示了如何使用JSON内容返回500个响应:

public async Task Invoke(HttpContext httpContext)
{
    if (<condition>)
    {
       context.Response.StatusCode = 500;  

       context.Response.ContentType = "application/json";

       string jsonString = JsonConvert.SerializeObject(<your DTO class>);

       await context.Response.WriteAsync(jsonString, Encoding.UTF8);

       // to stop futher pipeline execution 
       return;
    }

    await _next.Invoke(httpContext);
}
Run Code Online (Sandbox Code Playgroud)