Fuad Ahmad
Fuad Ahmad

Reputation: 33

Can i use routes.MapMvcAttributeRoutes(); on MVC4?

I try to create a controller on MVC4 and i need links on special attribute so when I open RouteConfig.cs I can't found this : routes.MapMvcAttributeRoutes(); and give me an error . So how can i make a special attribute to the each control and action on MVC 4

Upvotes: 0

Views: 1983

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

MapMvcAttributeRoutes() extension method only available in MVC version 5 or higher, because RouteCollectionAttributeRoutingExtensions class doesn't exist in previous versions. Using that method in MVC 4 or below will show this error:

'RouteCollection' does not contain a definition for 'MapMvcAttributeRoutes' and no extension method 'MapMvcAttributeRoutes' accepting a first argument of type 'RouteCollection' could be found.

If you want to use attribute routing in MVC versions older than MVC 5, install AttributeRouting package then use AddRoutesFromController() method to add controller name into routing configuration inside RegisterRoutes method (ControllerName belongs to any controller class name):

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapAttributeRoutes(config =>
    {
        config.AddRoutesFromController<ControllerName>();
    });
}

Then, you can use RouteAttribute (and RoutePrefixAttribute) similar to MVC 5 fashion:

[RoutePrefix("Cars")]
public class CarsController : Controller
{
    [Route("Cars/Index")]
    public ActionResult Index()
    {
        // do something
    }
}

You can found detailed information of AttributeRouting package usage here.

Upvotes: 2

Related Questions