ASP.NET MVC 5路由可选参数

时间:2015-12-14 10:56:37

标签: 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);
}

它工作正常,但我想让参数可选。根据{{​​3}}在路径中的参数名称末尾添加一个问题点应该足够了

[Route("Rest/GetName/{name?}")]

这样一来,如果我没有提供可选参数,我会收到错误,所以

.../Rest/GetName/AnyName --> ok
.../Rest/GetName/ --> error (see below)
  

{"消息":"未找到与请求URI匹配的HTTP资源' documentation'。"," MessageDetail":"控制器上没有找到任何操作'休息'与请求匹配。"}

2 个答案:

答案 0 :(得分:14)

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 :(得分:0)

有许多可能的解决方案:

  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. 2. 首先在控制器上设置PreFix

        [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);
             }
         }
    

    希望这有助于您解决问题。谢谢