ASP.NET MVC 5路由可选参数

Nai*_*gel 7 c# asp.net-mvc routing asp.net-mvc-routing

我在ApiController中有一个Action,我想从一个特定的链接调用,所以我创建了这个简单的路径

[Route("Rest/GetName/{name}")]
public IHttpActionResult GetName(string name) {
    // cut - code here is trivial but long, I just fill in an object to return as Json code
    return Json(myObject);
}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我想使参数可选.根据文档在路径中的参数名称末尾添加一个问题点就足够了

[Route("Rest/GetName/{name?}")]
Run Code Online (Sandbox Code Playgroud)

这样,如果我不提供可选参数,我会收到错误,所以

.../Rest/GetName/AnyName --> ok
.../Rest/GetName/ --> error (see below)
Run Code Online (Sandbox Code Playgroud)

{"Message":"找不到与请求URI匹配的HTTP资源' https:// localhost/miApp/Rest/GetName '.","MessageDetail":"在控制器'Rest'上找不到与之匹配的操作请求."}

Vad*_*nov 16

Web API需要显式设置可选值,即使对于可空类型和类也是如此.

使用默认值为可选参数:

[Route("Rest/GetName/{name?}")]
public IHttpActionResult GetName(string name = null) {
    // cut - code here is trivial but long, I just fill in an object to return as Json code
    return Json(myObject);
}
Run Code Online (Sandbox Code Playgroud)

不要忘记路由注册:

httpConfig.MapHttpAttributeRoutes()
Run Code Online (Sandbox Code Playgroud)