c# - 为 API 请求禁用 StatusCodePages 中间件
问题描述
我正在使用 asp.net core 2.1,StatusCodePagesMiddleware.cs的来源
if (!statusCodeFeature.Enabled)
{
// Check if the feature is still available because other middleware (such as a web API written in MVC) could
// have disabled the feature to prevent HTML status code responses from showing up to an API client.
return;
}
似乎提出了 API 中间件禁用处理程序的假设,但事实并非如此。是否有一种更简洁的方法可以仅为 MVC 请求启用中间件,而无需调用app.UseWhen
和检查路径字符串,或者这是最好的方法?
app.UseWhen(
context => !context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase),
builder => builder.UseStatusCodePagesWithReExecute("/.../{0}"));
解决方案
这在某种程度上取决于解释,但我想说该评论只是暗示某些东西可能会禁用该功能,但默认情况下并不是任何东西实际上会起作用。
我认为没有任何明显更清洁的东西 - 你有什么是有道理的,但另一种选择是使用一个自定义中间件来关闭该功能。这可能是这样的:
public void Configure(IApplicationBuilder app)
{
// ...
app.UseStatusCodePagesWithReExecute("/.../{0}");
app.Use(async (ctx, next) =>
{
if (ctx.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase))
{
var statusCodeFeature = ctx.Features.Get<IStatusCodePagesFeature>();
if (statusCodeFeature != null && statusCodeFeature.Enabled)
statusCodeFeature.Enabled = false;
}
await next();
});
// ...
app.UseMvc();
// ...
}
推荐阅读
- mysql - 在状态的发布请求中发送日期始终返回 NULL
- python - 使用给定的输入列表对 DataFrame 列进行排序
- powerbi - 如何在 power bi visuals 中显示当前日期和时间?
- angularjs - 使用搜索框导航到其他状态
- django - 如何自定义 django 管理员
- jelastic - Jelastic GC 代理是否为新创建的“Java 引擎”环境自动启用?
- javascript - 如何通过js重新触发animationTransform?
- image - 如何对下载时会损坏的图像进行“锁定”?
- powershell - 将 Active Directory 配置设置保存到文件
- ios - iOS应用程序的收据验证代码,不起作用