Srinivas Rathikrindi
Srinivas Rathikrindi

Reputation: 576

MVC routes with static Prefix

I have two routes in my routeConfig files as follow.

  1. Route with admin prefix which handles request for admin part
  2. default Route without a prefix, for which I have added a datatoken to map routes in candidate Area
routes.MapRoute(
                    name: "admin",
                    url: "Admin/{controller}/{action}/{id}",
                    defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional },
                    namespaces: new[] { "abc.namespace1" }
                );

                routes.MapRoute(
                    name: "default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional },
                    namespaces: new[] { "abc.namespace2" }
                ).DataTokens.Add("area", "Candidate");

But the problem is when i type in a url localhost/MyApp/Admin/Home/Index it is hitting the controller in abc.namespace1 (which is expected) and localhost/MyApp/Home/Index also hitting Home controller inside abc.namespace1 instead of HomeController inside abc.namespace2 in candidate Area.

What i want to do here is handle all routes with Admin prefix with controllers inside abc.namespace1 and all routes without any prefix with controllers inside abc.namespace2 which is my candiate Area.

regards

Upvotes: 2

Views: 904

Answers (1)

NightOwl888
NightOwl888

Reputation: 56849

I believe this might have something to do with the way you have specified your namespaces. The namespace must be for where the controller classes reside.

The pattern is typically <namespace of area>.<area name>.<controller namespace>

For example, in a project with an area named "Admin", the namespace must be:

"MvcMusicStore.Areas.Admin.Controllers"

In my experience, the conventions for how areas are set up are pretty strict. You should not set up the route in an AreaRegistration rather than the root of your project in order to get it to work.

public class CandidateAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Candidate";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Candidate_default",
            "{controller}/{action}/{id}",
            new { controller = "Account", action = "Login", id = UrlParameter.Optional },
            new string[] { "<project name>.Areas.Candidate.Controllers" }
        );
    }
}

Areas are convention-based. If you deviate too far from the anticipated conventions, they simply don't function.

Upvotes: 0

Related Questions