首页 > 解决方案 > 除了验证用户提供的值之外,如何让我的正则表达式路由属性匹配一个空值?

问题描述

我有这个控制器和动作:

[Route("categories")]
public class CategoriesController : Controller
{
    [HttpGet("{*category:regex(^[[A-Za-z0-9/]]*$)}")]
    public IActionResult ViewObjectsInCategory([FromRoute] string category)
    {
        return Ok(category ?? ""); // for now, just echo what you inputted
    }
}

我打算此操作接受以下 url 路由:

/类别
/类别/美国广播公司
/类别/abc/def
/类别/abc/def/1234/ghi

本质上,用户可以在 url 后面添加他们想要的任何内容/categories(包括任何内容),只要它是大写字母、小写字母、数字或正斜杠即可。如果用户输入无效字符,他们应该收到 404。

/categories发布的代码将正确路由我列出的除第一个条目 ( )之外的所有请求。当我希望它执行我的操作时,它会返回 404。

查看日志,ASP.Net 核心绝对拒绝我的行动路线:

信息:Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      请求开始 HTTP/1.1 GET http://localhost:5000/categories
dbug:Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[0]
      检测到通配符,所有带有主机的请求都将被允许。
dbug:Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[4]
      请求路径 /categories 与支持的文件类型不匹配
dbug:Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1001]
      为请求路径“/类别”找到 1 个候选人
dbug:Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1003]
      具有路由模式'categories/{*category:regex(^[A-Za-z0-9/]*$)}'的端点'MyApp.Controllers.CategoriesController.ViewObjectsInCategory (MyApp)'被约束'category'拒绝:' Microsoft.AspNetCore.Routing.Constraints.RegexInlineRouteConstraint',请求路径'/categories'的值为'(null)'
dbug:Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1004]
      路由模式为“categories/{*category:regex(^[A-Za-z0-9/]*$)}”的端点“MyApp.Controllers.CategoriesController.ViewObjectsInCategory (MyApp)”对请求路径无效“/类别'
dbug:Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware[2]
      请求不匹配任何端点

我该怎么做才能使此路由属性既接受“空”值(/categories),同时又验证(如果存在)任何用户输入的值都没有无效字符?

标签: c#asp.net-coreurl-routing

解决方案


推荐阅读