Search code examples
asp.netasp.net-mvcasp.net-web-apiasp.net-web-api2attributerouting

Default route when using ASP.NET MVC attribute routing


I'm using attribute routing with Web API, and everything works as expected if I request the URL /myapi/list with the following controller:

[RoutePrefix("myapi")]
public class MyController : ApiController
{
    [HttpGet]
    [Route("list")]
    public async Task<string> Get()
    {
       // Return result
    }
}

However, I would like my Get() method to be the default, i.e. when requesting the URL /myapi (without the /list part).

But if I remove the "list" part of the Route attribute like so...

[RoutePrefix("myapi")]
public class MyController : ApiController
{
    [HttpGet]
    [Route] // Default route
    public async Task<string> Get()
    {
       // Return result
    }
}

...I get a 403.14 error saying

"The Web server is configured to not list the contents of this directory."

Any ideas of what might be causing this?

Thanks!

Edit: If I request the API controller using the default route pattern like /api/myapi, it maps to the Get() method as expected.

Default route is registered after the attribute routes:

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

Solution

  • As pointed out by haim770 in the comments: the problem was that I had a physical folder with the same name as the route prefix.

    Renaming either the folder or the route prefix solved the problem.

    I guess an alternative would have been to tweak the route/handler order to ensure attribute routes take precedence over physical paths.