【问题标题】:ASP.Net Core 2.0 - How to return custom json or xml response from middleware?ASP.Net Core 2.0 - 如何从中间件返回自定义 json 或 xml 响应?
【发布时间】:2018-08-24 14:09:25
【问题描述】:

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

【问题讨论】:

  • 请将有关标题的问题作为单独的question 发布在 SO 上。

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


【解决方案1】:

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

【讨论】:

  • 感谢解决方案,非常有帮助!是否有机会在没有 if(...) 语句的情况下动态返回 json 或 xml?我注册了一个XmlDataContractSerializerOutputFormatter,但它只在services.AddMvc(...)的范围内
  • @philipp-fx 我添加了if 只是为了强调中间件可以返回结果或调用管道中的下一个中间件。关于动态响应格式,我不太清楚,但假设最好的方法是根据 Accept 请求 HTTP 标头手动选择 Response.ContentType。对于 XML 格式,它将是 application/xml
  • 谢谢Set,我理解您的if (&lt;condition&gt;),我指的不是if 声明。在您的代码中返回一个 json。考虑到 xml 时,很明显添加一个 if 语句并根据标头处理 json 和 xml。但是,我更喜欢更少的代码行并避免这种 if 语句。是否可以在更全球范围内处理接受的媒体类型 json、xml 或任何其他?
猜你喜欢
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 2020-04-23
  • 2018-10-21
  • 2019-10-28
  • 2021-09-21
  • 1970-01-01
  • 2018-08-15
相关资源
最近更新 更多