Bartek Chyży
Bartek Chyży

Reputation: 541

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?

Upvotes: 3

Views: 3313

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 26989

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.

Upvotes: 2

Kahbazi
Kahbazi

Reputation: 14995

You need to add a route to your route collections instead of using route attributes

routes.MapRoute(
            "Route",
            "prefix/{controller}/{action}",
            new { controller = "Specializations", action = "Index" });

Upvotes: 2

Related Questions