2
votes

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 }
        );
    }
2
Do you have a physical/virtual directory named myapi? - haim770
@haim770 Hmm, indeed, that seems to be the problem! If I rename my route prefix, the default route works as expected! Thanks so much for your help! Feel free to post it as an answer and I'll accept it. :) - Ted Nyberg
It just reminded me of stackoverflow.com/a/24533925/1625737 - Not sure whether it's qualifies as duplicate though - haim770

2 Answers

3
votes

Use

[Route("")]

for the default route

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

Reference: Attribute Routing in ASP.NET Web API 2 : Route Prefixes

1
votes

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.