为 API 请求禁用 StatusCodePages 中间件

Rit*_*o2k 4 c# asp.net-core

我正在使用 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;
}
Run Code Online (Sandbox Code Playgroud)

似乎提出 API 中间件禁用处理程序的假设,但事实并非如此。是否有一种更简洁的方法可以只为 MVC 请求启用中间件,而无需调用app.UseWhen和检查路径字符串,或者这是最好的方法?

app.UseWhen(
    context => !context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase),
    builder => builder.UseStatusCodePagesWithReExecute("/.../{0}"));
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 5

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

我不认为有任何明显更干净的东西 - 你所拥有的东西是有道理的,但另一种选择是使用自定义中间件来关闭该功能。这可能是这样的:

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();
    // ...
}
Run Code Online (Sandbox Code Playgroud)