c# - 如果我的标头中根本没有 Content-Type,ASP.NET Core Web API 管道的流程是什么?
问题描述
我正在尝试解决这个问题,如果客户端在到达我的控制器之前在其标题中没有内容类型,我想显示我的 OWN 错误消息。不是 [ApiController] 通用问题详细信息消息,而是完全我自己的 JSON 对象。我一直试图弄清楚这一点,我至少知道在我的控制器上使用 [ApiController] 属性会给我 4XX 错误代码的问题详细信息响应。我删除了这个,现在我有空的响应体。我想要与响应相同的状态代码,只是不同的主体/对象。解决这个问题的最佳方法是什么?我想知道流程,这样我就可以事先发现这个错误并用我自己的 JSON 对象返回我的响应
解决方案
您可以使用中间件解决此问题。以下是您可以创建并连接到 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>();
推荐阅读
- android - 运算符 '*' 不能应用于 'android.widget.RadioButton', 'int'
- amazon-web-services - AWS 实例随机超时
- c# - 使用条件唯一约束保存实体时出现循环依赖错误
- ios - 带有 GLSL 的 CIKernel 白色像素
- android - 卡视图的最后一行未在所有设备中显示
- laravel - Laravel - 调用全部时查询模型
- javascript - 响应式图像缩略图
- ios - 在 iOS 应用程序中从 webkit 获取 html 源代码
- botframework - 如何使您的机器人对频道中的特定用户可见
- ios - 不能在 inout 函数中使用 SKShapeNode