ASP.NET MVC 5 路由可选参数

ASP.NET MVC 5 routing optional parameters

我的 ApiController 中有一个 Action,我想从特定 link 调用它,所以我创建了这个简单的路由

[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 需要显式设置可选值,即使对于可空类型和 类.

对可选参数使用默认值:

[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()

有很多可能的解决方案:

  1. 尝试可选参数

       [Route("Rest/GetName/{name?}")]
       public IHttpActionResult GetName(string name = null) {
           // cut - code here        is trivial but long, I just fill in an               
           obj ect to return as 
           `enter code here`Json code
           return Json(myObject);
             }
    

2.先在控制器上设置前缀

    [RoutePrefix("api/Rest")]
    [Authorize]
    public class RestController : ApiController
    {
         [Route("/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);
         }
     }

3.在路由中的动作名前写参数

   [RoutePrefix("api/Rest")]
    [Authorize]
    public class RestController : ApiController
    {
         [Route("{name}/GetName")]
         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);
         }
     }

希望这能帮助您解决 problem.Thanks