Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-mvc-routing

Can Attribute Routing in ASP.Net MVC 5 Be Used Without Web API


I have an MVC project that I am trying to use Attribute Routing in however I get keep getting 404's for the valid url's.

I have google to see what the common problems with Attribute Routing are to see if I am missing something obvious and most answers seemed to be make sure the route registration is as follows:

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

With the line routes.MapMvCAttributeRoutes() being the code that searches the controllers for the routing attributes and configures the routes.

I have also seen a few references to Web API as I believe the attributes can be used in APIController's as well.

However the following article seems to suggest that it can be used in Mvc alone since there is no mention of Web API.

Attribute Routing in ASP.Net MVC 5

So is there a dependency and do you need to have Web API to get the Route Attributes working in MVC?

UPDATE

Using the following stripped down code:

[Route("hello")]
public class SomeController : Controller
{
    // GET: Some
    public string Index()
    {
        return "world!";
    }
}

I can get a valid response of 'world!' for the url 'localhost:58268/hello', which is a start. So it looks like you can have Attribute Routing in Mvc 5 without the dependency on Web API.

I must have made an error in defining the Route in the case of the actual code.


Solution

  • Yes, you can use MVC attribute routing without webAPI. It is a separate feature from WebAPI attribute routing. Both got introduced around at same time in WebAPI 2 and MVC 5.

    Web API attribute routing is a bit more flexible than MVC, for many scenarios things should work just fine.

    Note that in MVC Core, the Web API and MVC frameworks got merged.There is a single attribute routing feature which is a LOT more flexible and solves most of the limitations in the previous frameworks.