首页 > 解决方案 > 如果我的标头中根本没有 Content-Type,ASP.NET Core Web API 管道的流程是什么?

问题描述

我正在尝试解决这个问题,如果客户端在到达我的控制器之前在其标题中没有内容类型,我想显示我的 OWN 错误消息。不是 [ApiController] 通用问题详细信息消息,而是完全我自己的 JSON 对象。我一直试图弄清楚这一点,我至少知道在我的控制器上使用 [ApiController] 属性会给我 4XX 错误代码的问题详细信息响应。我删除了这个,现在我有空的响应体。我想要与响应相同的状态代码,只是不同的主体/对象。解决这个问题的最佳方法是什么?我想知道流程,这样我就可以事先发现这个错误并用我自己的 JSON 对象返回我的响应

标签: c#asp.net-mvcapiasp.net-coreasp.net-web-api

解决方案


您可以使用中间件解决此问题。以下是您可以创建并连接到 HTTP 管道的示例中间件类

public class InterceptContentType
{
    private RequestDelegate _next;

    public InterceptContentType(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // This is where you can intercept the content type as shown below
        // and perform what you need
        context.Request.Headers[HeaderNames.ContentType] = "application/xml";
        await _next.Invoke(context);
    }
}

将此类连接到您的 HTTP 管道就像将以下语句添加到 Startup.cs 类中的 Configure() 方法一样简单

app.UseMiddleware<InterceptContentType>();

推荐阅读