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

Add route prefix to all actions in controller using one attribute


Here is my controller

public class SpecializationsController : Controller
{    
    public ActionResult Action1()
    {
        //body
    }

    public ActionResult Action2()
    {
        //body
    }

Default url for Action1 is of course /Specialization/Action1. I want to add prefix to all Actions in my controller to make my ulr like /prefix/Specialization/Action1.

I tried to add [RoutePrefix("prefix")] to my controller but it doesn't work. I would like to avoid adding [Route] attribute for each action in my controller. So how can I add this prefix?


Solution

  • I would create Areas:

    Areas are an ASP.NET MVC feature used to organize related functionality into a group as a separate namespace (for routing) and folder structure (for views). Using areas creates a hierarchy for the purpose of routing by adding another route parameter

    I know you may think this is an overkill for simply having a "prefix" but the reason I suggest this approach is because if you have the need to add a "prefix", chances are you have the need to separate the views, models etc. as well.