ASP.NET MVC and ASP.NET Web API 2 Attribute Routing Not Working

Recently I had a number of problems with the routing mechanisms clashing when implementing a site that contained both ASP.NET MVC and ASP.NET Web API 2. I thought I’d share my troubleshooting steps here in case this helps others (and also because I’m bound to forget them).

  1. Make sure you’ve actually registered Web API 2 and MVC routing with the following commands
    • For Web API 2 –
      • MapHttpAttributeRoutes()
      • Routes.MapHttpRoute() (done after mapping attribute routing for Web API 2)
    • For MVC –
      • AreaRegistration.RegisterAllAreas() (to register areas if you are using them)
      • RouteTable.Routes.MapMvcAttributeRoutes()
      • RouteTable.Routes.MapRoute() (done after mapping attribute routing for MVC)
  2. When registering your routes for Web API 2, make sure you do it like so
    • DO this
      protected void Application_Start(object sender, EventArgs e)
      {
      /* Application Start Declarations Go Here */
      GlobalConfiguration.Configure(ConfigureRoutes);
      /* Application Start Declarations Go Here */
      }
       

      private void ConfigureRoutes(HttpConfiguration config)
      {
      /* Routes registered here */
      }

    • DON’T do this
      protected void Application_Start(object sender, EventArgs e)
      {
      /* Application Start Declarations Go Here */
      ConfigureRoutes(GlobalConfiguration.Configuration);
      /* Application Start Declarations Go Here */
      }
       

      private void ConfigureRoutes(HttpConfiguration config)
      {
      /* Routes registered here */
      }
       

  3. Register Web API 2 attribute routing before you register the MVC attribute routing – this didn’t happen to me but I understand it to be a common issue (found it here http://stackoverflow.com/questions/19907226/asp-net-webapi-2-attribute-routing-not-working)
    • Note – this doesn’t apply to the mappings done via “RegisterAllAreas()”, the Web API 2 routing can be done after this call is made
  4. If you declare a RoutePrefix attribute on an Web API 2 controller using the HTTP request actions like GET, POST, PUT etc. WILL NOT MATCH, you have to declare Route attributes on the actions for the RoutePrefix to be used
  5. If you’ve made the error of calling IAppBuilder.UseWebApi() in your OWIN startup file, remove it because it breaks MVC and Web API 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s