C# 和 ASP.NET MVC 5:使用正则表达式的路由 URL 中的可选字符串

问题描述 投票:0回答:1

我正在尝试确定是否可以使用 C# 和 ASP.NET MVC 5 在给定的路由 URL 中包含字符串的可选部分。

例如:

[HttpGet]
[Route("~/hot-dogs{withMustard:regex(-with-mustard?)}/", Name = "HotDogOrder")]
public async Task<ActionResult> HotDogOrder(string withMustard= null)

我希望路线适用于:

https://www.domain.tld/hot-dogs/
https://www.domain.tld/hot-dogs-with-mustard/

如果我使用那个正则表达式,它会匹配

https://www.domain.tld/hot-dogs-with-mustard/
,但不会匹配
https://www.domain.tld/hot-dogs/

我不想将

with-mustard
添加为看起来像子目录的内容,例如:

https://www.domain.tld/hot-dogs/with-mustard/

这可能吗?我试过使用可选的

?
*
,但似乎无法正常工作。我想使用
Route
装饰器,而不必为每个可能的选项创建不同的功能。

任何想法,或者这是不可能的?

我已经尝试了各种正则表达式值,但似乎无法找到适用于这两种用例的东西

c# asp.net-mvc-5
1个回答
2
投票

您可以使用两条路线并检查 Path 属性。
我不认为正则表达式适用于整个路由,它适用于单个参数。

[HttpGet]
    [Route("hot-dogs")]
    [Route("hot-dogs-with-mustard")]
    public ActionResult<string> DoSomething() {
        var path = Request.Path; // 
    }    

也试试这个,也适用于芥末番茄酱热狗

    [HttpGet]
    [Route("hot-dogs")]
    [Route("hot-dogs{actionPath:regex(^(-with(-(ketchup|mustard|relish))+)$)}")]
    public ActionResult<string> DoSomething(string? actionPath) {
        
        return Ok(actionPath);
    }
© www.soinside.com 2019 - 2024. All rights reserved.