Asp.Net Core 自定义 Route 检查

创建 Asp.Net Core API项目
nuget 引用 NSwag.AspNetCore ,这个是一个api文档包 Startup类注册服务
ConfigureServices方法

            services.AddSwaggerDocument(config =>
            {
                config.PostProcess = document =>
                {
                    document.Info.Version = "v1";
                    document.Info.Title = "ToDo API";
                    document.Info.Description = "A simple ASP.NET Core web API";
                    document.Info.TermsOfService = "None";
                    document.Info.Contact = new NSwag.OpenApiContact
                    {
                        Name = "Shayne Boyer",
                        Email = string.Empty,
                        Url = "https://twitter.com/spboyer"
                    };
                    document.Info.License = new NSwag.OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = "https://example.com/license"
                    };
                };
            });

Configure方法

       app.UseOpenApi();
       app.UseSwaggerUi3();

创建API控制器 TestController

    [ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {


        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet("RouteTest/{no:StringLength20}")]
        public IActionResult RouteTest(string no)
        {
            return Ok();
        }
    }

创建 StringLength20 路由检查类 RouteDirection有两种枚举类型分对应IncomingRequest、UrlGeneration 来自客户端的 URL。和 根据路由正在创建的 URL。
下面是官方的描述

          public class StringLength20 : IRouteConstraint
    {
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (RouteDirection.UrlGeneration == routeDirection)
            {
                string v = values[routeKey].ToString();
                if (v.Length == 20)
                {
                    return true;
                }
            }
            if (RouteDirection.IncomingRequest == routeDirection)
            {
                string v = values[routeKey].ToString();
                if (v.Length == 20)
                {
                    return true;
                }
            }

            return false;
        }
    }

注册路由的检查服务

          services.AddRouting(routing => {
                routing.ConstraintMap.Add("StringLength20", typeof(StringLength20));
            });

可以看到 api的路由检查枚举值是IncomingRequest

检查未通过返回404

有同学会有疑问RouteDirection.UrlGeneration 的作用率,动态路由的时候你就用得上了

posted @ 2020-05-10 21:54  Blog老中医  阅读(503)  评论(0编辑  收藏  举报