为了账号安全,请及时绑定邮箱和手机立即绑定

为 API 请求禁用 StatusCodePages 中间件

为 API 请求禁用 StatusCodePages 中间件

C#
慕森王 2022-01-09 16:35:28
我正在使用 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}"));
查看完整描述

2 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

对我来说正确的答案是UseStatusCodePagesWithReExecute在 Startup.cs 中使用 plain ,但在错误控制器中改变处理方式。这使我可以返回纯文本内容以显示 API 错误,但为用户保留友好的视图。


启动.cs


app.UseStatusCodePagesWithReExecute("/error/{0}");

错误控制器:


[HttpGet("error/{statusCode:int}")]

public IActionResult Error(int statusCode)

{

    var statusCodeFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();


    var exceptionDataFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();


    // ... Other logging and stuff


    IActionResult actionResult;


    if (statusCodeFeature == null || statusCodeFeature.OriginalPath.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase))

    {

        actionResult = Content($"The request could not be processed: {statusCode.ToString(CultureInfo.InvariantCulture)}");

    }

    else

    {

        ViewBag.StatusCode = statusCode;


        actionResult = View();

    }


    return actionResult;

}


查看完整回答
反对 回复 2022-01-09
?
慕田峪4524236

TA贡献1875条经验 获得超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();

    // ...

}


查看完整回答
反对 回复 2022-01-09
  • 2 回答
  • 0 关注
  • 249 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号