ASP.Net Core 2.0-如何从中间件返回自定义json或xml响应? [英] ASP.Net Core 2.0 - How to return custom json or xml response from middleware?

查看:456
本文介绍了ASP.Net Core 2.0-如何从中间件返回自定义json或xml响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In ASP.Net Core 2.0, I am trying to return a message formatted as json or xml with a status code. I have no problems returning a custom message from a controller, but I don't know how to deal with it in a middleware.

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

My middleware class looks like this so far:

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

推荐答案

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

To fill response in middleware use httpContext.Response property that returns HttpResponse object for this request. The following code shows how to return 500 response with JSON content:

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

这篇关于ASP.Net Core 2.0-如何从中间件返回自定义json或xml响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆