4

Overview

I'm currently trying to get attribute routing to work with my api controllers. It doesn't appear to be working, and I'm unsure why. I'm not sure if I'm missing a crucial step, or what the problem could be.

Problem

I'm trying to hit localhost/api/user/custom?test=1 but I get a 404 (I expect this to work)

If I hit localhost/api/customapi?test=1 I successfully get into my method

Why does the first url not work?

Setup

My setup is as follows:

CustomController.cs

[System.Web.Mvc.RoutePrefix("api")] public class CustomApiController : ApiController { [System.Web.Mvc.Route("user/custom")] [System.Web.Http.HttpGet] public async Task<CustomResponse> Get([FromUri] CustomRequest request) { //Work } } 

WebApiConfig.cs

public static class WebApiConfig { public static void Register(HttpConfiguration config) { ...(json serializer settings)... // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } 

RouteConfig.cs

public static class RouteConfig { public static void Register(RouteCollection routes, bool registerAreas = true) { if(registerAreas) { AreaRegistration.RegisterAllAreas(); } //Ignore Routes ... //Register specific routes routes.MapRoute("HomeUrl", "home", new { controller = "Home", action = "Index" }); . . routes.MapRoute( "Default", //Route name "{controller}/{action}/{id}", //URL with parameters new { controller = "Home", action = "Index", id =UrlParameter.Optional } ); } } 

Global.asax.cs

public class Global : HttpApplication { protected void Application_Start() { ....(app startup stuff)... GlobalConfiguration.Configure(WebApiConfig.Register); BundleConfig.Register(BundleTable.Bundles); ....(more app startup stuff)... RouteConfig.Register(RouteTable.Routes); } } 

1 Answer 1

12

I was using the wrong namespace in my routes.

[System.Web.Http.Route("")] //Use this namespace for Web API 2 [System.Web.Mvc.Route("")] [System.Web.Http.RoutePrefix("api")] //Use this namespace Web API 2 [System.Web.Mvc.RoutePrefix("api")] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this -- I've come here after tearing my hair out with an MVC routing problem (it turned out to be the same as yours, but the other way around). I couldn't figure out why one of my controllers in an MVC site wasn't being picked up by the routing. Eventually I found that it was using Http.Route instead of Mvc.Route. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.