Web api 2属性路由即使在WebApiConfig中配置也无法正常工作

时间:2018-01-30 07:55:05

标签: asp.net-web-api routing asp.net-web-api2 attributerouting

我不明白为什么我的属性路由不起作用。如果我转到“http://localhost:56125/api/Contact/1682”,那么我会看到测试控制器显示“value1”和“value2”,但如果我转到http://localhost:56125/api/contacts/1682那么我会得到No HTTP resource was found that matches the request URI 'http://localhost:56125/api/contacts/1682'而我不会明白为什么?

在ContactController.cs中:

public class ContactController : ApiController
{
    private readonly NGSystemRepository _repo = new NGSystemRepository();

    // GET: api/Contact
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }


    [Route("api/contacts/{contactId}")]
    [HttpGet]
    public ContactInformation GetContactInformation(int contactNumber)
    {
        return _repo.GetContact(contactNumber);
    }
}

在WebApiConfig中:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

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

1 个答案:

答案 0 :(得分:0)

哎呀!愚蠢的错误。我没有将属性属性名称(contactId)与方法属性名称(contactNumber)匹配。

我的控制器操作应该只是:

[Route("api/contacts/{contactId}")]
[HttpGet]
public ContactInformation GetContactInformation(int contactId)
{
    return _repo.GetContact(contactNumber);
}