Search code examples
asp.net-web-apiroutesasp.net-web-api2attributerouting

Web api 2 attribute routing not working even with it configured in WebApiConfig


I don't understand why my attribute routing isn't working. If I go to 'http://localhost:56125/api/Contact/1682' then I get the test controller with "value1" and "value2" shown, but if I go to http://localhost:56125/api/contacts/1682 then I get No HTTP resource was found that matches the request URI 'http://localhost:56125/api/contacts/1682' and I don't understand why?

In 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);
    }
}

In 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 }
        );
    }
}

Solution

  • Argh! Stupid mistake. I didn't match the attribute property name (contactId) with the method property name (contactNumber).

    My controller action should simply be:

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