c# - 除了验证用户提供的值之外,如何让我的正则表达式路由属性匹配一个空值?
问题描述
我有这个控制器和动作:
[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
),同时又验证(如果存在)任何用户输入的值都没有无效字符?
解决方案
推荐阅读
- gitlab - GitLab CE:如何恢复或修复突然丢失的问题/合并请求的存储库?
- django - xamarin froms 从 django rest 框架解析 JSON
- c# - SQL Server Management Studio 空值
- javascript - 如何实现 Webrtc 实时视频过滤器
- java - 测量运动过程中消耗的能量的程序
- scala - 在 testOnly 之前重新编译 build.sbt 和 project/
- f# - 如何结合选项和结果
- sed - 提取双引号内的字符串 - 为什么 sed 命令不起作用而 grep -o 起作用?
- reactjs - 反应路由器 dom v6 未在 mapStateToProps 中填充 ownProps
- angular - Angular 10 子组件仅用于父组件