代码之家  ›  专栏  ›  技术社区  ›  Ritmo2k

为API请求禁用StatusCodePages中间件

  •  1
  • Ritmo2k  · 技术社区  · 6 年前

    我正在使用asp.net核心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}"));
    
    1 回复  |  直到 6 年前
        1
  •  5
  •   Kirk Larkin    6 年前

    这在某种程度上可以归结为解释,但我想说,这一评论只是在暗示 能够

    我不认为有任何明显更干净的东西-你有什么是有意义的,但另一个选择是使用一个自定义中间件,切换功能关闭。可能是这样的:

    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();
        // ...
    }
    
        2
  •  0
  •   gbro3n    4 年前

    对我来说,正确的答案是用普通的 UseStatusCodePagesWithReExecute

    启动.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;
    }