2014-01-18 57 views
1

我正在使用asp.net MVC 5與Web API 2.我測試了新的屬性路由,這似乎很簡單。我遵循MSDN入門鏈接,但仍然無法完成簡單的設置。asp.net web api 2 url路由屬性找不到時

在API配置文件:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 

在API控制器:

public class RecruitingController : ApiController 
{ 
    ...snip... 
    [Route("Recruiting/countries/all/")] 
    [ResponseType(typeof(List<Country>))] 
    public async Task<IHttpActionResult> GetCountries() 
    { 
     var countries = ctx.Countries.ToList(); 
     if (countries.Count == 0) 
     { 
      return NotFound(); 
     } 

     return Ok(countries); 
    } 

} 

在我看來,我呼籲通過AJAX的路由。在鉻開發工具,它試圖擊中這條路線:

http://localhost:43736/api/Recruiting/countries/all/ 

我得到一個404響應。

我在哪裏搞亂了這裏的語法?我有Ajax調用就像這樣:

$.getJSON(apiBaseUrl + "/countries/all/", function (data) { 
    $.each(data, function() { 
     var dropdownCountry = new DropdownCountry(); 
     $.each(this, function (k, v) { 
      if (k === "Name") { 
       dropdownCountry.name = v; 
      } 
      if (k === "Key") { 
       dropdownCountry.key = v; 
      } 
     }); 
     self.orgCountryDdl.push(dropdownCountry); 

    }); 
    alert(DropdownCountry()); 
}); 

apiBaseUrl是「API /招聘」

回答

3

你似乎使用您的請求URL中的常規路線...您的請求URL想http://localhost:43736/Recruiting/countries/all/ ...請注意,匹配傳統路由的請求永遠無法到達屬性控制器/操作。

+0

ohhhh ..菜鳥錯誤.. – ledgeJumper

0

您也可以在課程級別添加API基本URL屬性。

那麼所有的方法屬性都是在類級別構建的。