我正在使用带有 Web API 2 的 asp.net MVC 5。我正在测试新的属性路由,这看起来很简单。我关注了 msdn 介绍性链接,但仍然无法进行非常简单的设置。
在 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 调用路由。在 chrome 开发者工具中,它试图走这条路:
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/recruiting'