我的 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);
}
它工作正常,但我想将参数设为可选。根据documentation在路由中的参数名末尾加一个问号点应该就可以了
[Route("Rest/GetName/{name?}")]
如果我不提供可选参数,这样我会得到一个错误,所以
.../Rest/GetName/AnyName --> ok
.../Rest/GetName/ --> error (see below)
{"Message":"No HTTP resource was found that matches the request URI 'https://localhost/miApp/Rest/GetName'.","MessageDetail":"No action was found on the controller 'Rest' that matches the request."}
最佳答案
Web API 需要显式设置可选值,即使对于可为 null 的类型和类也是如此。
对可选参数使用默认值:
[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);
}
不要忘记路由注册:
httpConfig.MapHttpAttributeRoutes()
关于c# - ASP.NET MVC 5 路由可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265248/