Carlitrosss
Carlitrosss

Reputation: 176

WebApi2 RoutePrefix and endpoint Route = Not found

I have decorated my api controller such as:

[RoutePrefix("api/admin/notification")] public class LanguageController : BaseController

Inside, I have this GET endpoint:

[HttpGet]
[Route("app/{productGuid}")]
public async Task<IHttpActionResult> GetAllNotificationsForApp([FromUri]string productGuid)

Now, I am assuming the correct way of accessing this resource is:

GET http://[api-url]/api/admin/notification/app/someguid

However, this yields a 404.

What I have tried:

-Removing [FromUri]

-Passing productGuid as part of querystring, i.e .../app?productGuid=something (as opposed to /app/{productGuid})

Yes, I am using config.MapHttpAttributeRoutes(); and I've verified other api controllers that also use RoutePrefix to be working.

Am I missing something?

Upvotes: 2

Views: 876

Answers (2)

Carlitrosss
Carlitrosss

Reputation: 176

Turns out you can't have two api controllers with the same class name, even if they are mapped to different routes.

I had another controller named LanguageController, in a different namespace and mapped to a different route; I had to rename one of them to make it work.

Based on Different RoutePrefix, same controller name

Upvotes: 1

Nkosi
Nkosi

Reputation: 246998

[FromUri] is used to force Web API to read a complex type from the URI. Removing it should have worked.

You could also look into changing the parameter from string to Guid and applying a proper constraint to the placeholder in the route. ie: [Route("app/{productGuid:guid}")]

[RoutePrefix("api/admin/notification")]
public class LanguageController : BaseController {
    //GET: api/admin/notification/app/{guid}
    [HttpGet]
    [Route("app/{productGuid:guid}")]
    public async Task<IHttpActionResult> GetAllNotificationsForApp(Guid productGuid) {...}

}

Other things to check:

Make sure that config.MapHttpAttributeRoutes(); is done before your convention-based routes. The order is important as first match wins.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

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

Upvotes: 1

Related Questions