首页 文章

在Web API路由(和子 endpoints )上强制404

提问于
浏览
0

我正在寻找一种简单的方法来返回Web API中给定路由的所有请求的404错误,以及该路由中的所有 endpoints . 在我的场景中,我将有一个配置标志来打开和关闭它 . 它是一个使用Swagger / Swashbuckle的文档 endpoints ,并希望能够将其打开和关闭作为一种功能切换 .

<add key="EnableDocumentation" value="true|false" />

理想情况下,对于以/ swagger开头的所有路由(包括/swagger/ui/index.html),如果以上值为 false ,我想返回404

我在HttpConfiguration.Routes中尝试过IgnoreRoute,但这对于深度超过指定级别的路由不起作用 . 如果我忽略/ swagger,仍然可以访问/swagger/ui/index.html

有什么建议可以做到这一点吗?

谢谢!

2 回答

  • 1

    您可以通过编写自己的 custom HTTP module 来完成此操作 .

    在您的HTTP模块中,您可以检查传入的URL请求,如果网址与您的路由匹配,则返回404 .

    检查这些(只是为了了解如何编写自定义http模块)

  • 1

    我有一个类似的情况:

    • 我想安装Swashbuckle用于API文档

    • 我想在不删除Nuget包或重新部署API的情况下控制对Swagger的访问

    这导致我得到以下代码:

    public class SwaggerConfig
    {
        private const string AllowSwaggerUsageAppSetting = "AllowSwaggerAccess";
    
        public static void Register()
        {
            if (AllowSwaggerAccess)
            {
                Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration);
            }
    
            // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ...
        }
    
        private static bool AllowSwaggerAccess
        {
            get
            {
                bool _parsedValue;
    
                return bool.TryParse(ConfigurationManager.AppSettings[AllowSwaggerUsageAppSetting] ?? "false", out _parsedValue) && _parsedValue;
            }
        }
    }
    

    除非web.config的appSettings部分中有一个名为 AllowSwaggerAccessBool.Parse '能值为 true 的密钥,否则将忽略Swashbuckle引导程序,这意味着无法访问swagger文档,并且对API的请求返回404 .

    上面的代码基于Swashbuckle Nuget Package的v4 .

    如果从github下载代码,您可以看到Init方法负责设置路由:

    public static class Bootstrapper
    {
        public static void Init(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                "swagger_root",
                "swagger",
                null,
                null,
                new RedirectHandler("swagger/ui/index.html"));
    
            config.Routes.MapHttpRoute(
                "swagger_ui",
                "swagger/ui/{*uiPath}",
                null,
                new { uiPath = @".+" },
                new SwaggerUiHandler());
    
            config.Routes.MapHttpRoute(
                "swagger_versioned_api_docs",
                "swagger/{apiVersion}/api-docs/{resourceName}",
                new { resourceName = RouteParameter.Optional },
                null,
                new SwaggerSpecHandler());
    
            config.Routes.MapHttpRoute(
                "swagger_api_docs",
                "swagger/api-docs/{resourceName}",
                new { resourceName = RouteParameter.Optional },
                null,
                new SwaggerSpecHandler());
        }
    }
    

相关问题