首页 > 解决方案 > 为 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}"));

标签: c#asp.net-core

解决方案


这在某种程度上取决于解释,但我想说该评论只是暗示某些东西可能会禁用该功能,但默认情况下并不是任何东西实际上会起作用。

我认为没有任何明显更清洁的东西 - 你有什么是有道理的,但另一种选择是使用一个自定义中间件来关闭该功能。这可能是这样的:

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();
    // ...
}

推荐阅读