除了验证用户提供的值外,如何获取正则表达式路由属性以匹配空值?

时间:2019-03-25 13:48:13

标签: c# asp.net-core url-routing

我有这个控制器和动作:

[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
    }
}

我打算执行此操作以接受以下网址路由:

/categories
/categories/abc
/categories/abc/def
/categories/abc/def/1234/ghi

从本质上讲,只要是大写字母,小写字母,数字或正斜杠,用户都可以在URL中将/categories放在任意位置(不包括任何内容)。如果用户输入的字符无效,他们应该收到404。

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

看看日志,ASP.Net核心绝对拒绝执行我的操作的路线:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/categories
dbug: Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[0]
      Wildcard detected, all requests with hosts will be allowed.
dbug: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[4]
      The request path /categories does not match a supported file type
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1001]
      1 candidate(s) found for the request path '/categories'
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1003]
      Endpoint 'MyApp.Controllers.CategoriesController.ViewObjectsInCategory (MyApp)' with route pattern 'categories/{*category:regex(^[A-Za-z0-9/]*$)}' was rejected by constraint 'category':'Microsoft.AspNetCore.Routing.Constraints.RegexInlineRouteConstraint' with value '(null)' for the request path '/categories'
dbug: Microsoft.AspNetCore.Routing.Matching.DfaMatcher[1004]
      Endpoint 'MyApp.Controllers.CategoriesController.ViewObjectsInCategory (MyApp)' with route pattern 'categories/{*category:regex(^[A-Za-z0-9/]*$)}' is not valid for the request path '/categories'
dbug: Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware[2]
      Request did not match any endpoints

如何使此路由属性既接受“空”值(/categories),又要验证是否存在(如果存在)任何用户输入的值都没有无效字符?

0 个答案:

没有答案