1

我正在使用带有 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'

4

2 回答 2

3

您似乎在您的请求 url 中使用了常规路由......您的请求 url 应该像http://localhost:43736/Recruiting/countries/all/......请注意,匹配常规路由的请求永远无法到达属性控制器/操作。

于 2014-01-18T17:54:15.163 回答
0

您也可以在类级别添加 API 基本 URL 属性。

然后所有方法属性都建立在类级别的方法属性之上。

于 2014-01-19T02:02:11.507 回答