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

时间:2018-03-15 16:47:58

标签: asp.net-core asp.net-core-2.0 asp.net-core-middleware request-pipeline

在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);
    }
}

1 个答案:

答案 0 :(得分:8)

要填充中间件中的响应,请使用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);
}