2017-01-03 45 views
2

在這裏,我嘗試使用調用的WebAPI控制器[路徑]屬性如何在控制器級別使用路由

爲什麼http://localhost:57997/Hello/Jan/1不是配置的路線 而http://localhost:57997/Hello/Jan獲取數據

using a = System.Web.Http; 

[a.Route("Hello/Jan")] 
public IEnumerable<Department> GetDepartmets() 
{ 
    var x = pro.GetDept(); 
    return x.ToList(); 
} 

[a.Route("Hello/Jan/{id?}")] 
public HttpResponseMessage GetDepartmets(int id) 
{ 
    if (id != null) 
     { 
      var x = pro.GetDeptById(id); 
      return Request.CreateResponse(HttpStatusCode.OK, x); 
     } 
     else 
      return Request.CreateResponse(HttpStatusCode.NotFound); 

} 
+0

啓用添加路由約束,看看它是否解決了這個問題'[a.Route(「你好/月/ {ID:INT ?}「)]'。你可能還需要包含Http {Verb}即:'[a.HttpGet]'。儘管公約應該根據行動名稱撿起它 – Nkosi

+0

你能展示一個更完整的控制器版本嗎? – Nkosi

回答

1

您的ID應匹配路由標識

[a.Route("Hello/Jan/{id}")] 
    public HttpResponseMessage GetDepartmets(int id) 
0

這裏是基於原來的控制器C什麼職位最小完全可驗證的例子看起來像使用屬性路由。

using a = System.Web.Http; 

[a.RoutePrefix("Hello/Jan")] //RoutePrefix used to group common route on controller 
public MyController : ApiController { 

    //...other code removed for brevity. ie: pro  

    //GET Hello/Jan 
    [a.HttpGet] 
    [a.Route("")] 
    public IHttpActionResult GetDepartmets() { 
     var departments = pro.GetDept().ToList(); 
     return Ok(departments); 
    } 

    //GET Hello/Jan/1 
    [a.HttpGet] 
    [a.Route("{id:int}")] //Already have a default route. No need to make this optional 
    public IHttpActionResult GetDepartmet(int id) { 
     var department = pro.GetDeptById(id); 
     if (department != null) { 
      return Ok(department); 
     } 

     return NotFound();  
    } 
} 

注:確保屬性的路由在WebApiConfig

//enable attribute routing 
config.MapHttpAttributeRoutes(); 

//...before other convention-based routes.