How to configure routes when using areas in asp.net mvc? - c#

Scenario:
I have 3 Areas named- Albums, Singers , Music
Now each of these areas have controllers with same name. For instance every area has LoginController.
Now currently I am getting following exception
Multiple types were found that match the controller named 'Login'
This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request.
If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.
This is auto generated Configuration by Visual Studio on Area Creation
public override string AreaName
{
get
{
return "Albums"
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Albums_Default"
"Client/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
This is my intial configuration in RoutesConfig.cs
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Application_Name" }
);
Now how to configure the routes that without any modification in url, the desired view is rendered.

Please try this one :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL
new { controller = "Home", action = "Index", id = "" }, // Defaults
new[]{"AreasDemoWeb.Controllers"} // Namespaces
);
}
Help Link 1
Help Link2

Related

Is it possible to host Asp.net MVC web App locally [duplicate]

In asp.net MVC the "homepage" (ie the route that displays when hitting www.foo.com) is set to Home/Index .
Where is this value stored?
How can I change the "homepage"?
Is there anything more elegant than using RedirectToRoute() in the Index action of the home controller?
I tried grepping for Home/Index in my project and couldn't find a reference, nor could I see anything in IIS (6). I looked at the default.aspx page in the root, but that didn't seem to do anything relevent.
Thanks
Look at the Default.aspx/Default.aspx.cs and the Global.asax.cs
You can set up a default route:
routes.MapRoute(
"Default", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index"} // Parameter defaults
);
Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.
ASP.NET Core
Routing is configured in the Configure method of the Startup class. To set the "homepage" simply add the following. This will cause users to be routed to the controller and action defined in the MapRoute method when/if they navigate to your site’s base URL, i.e., yoursite.com will route users to yoursite.com/foo/index:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=FooController}/{action=Index}/{id?}");
});
Pre-ASP.NET Core
Use the RegisterRoutes method located in either App_Start/RouteConfig.cs (MVC 3 and 4) or Global.asax.cs (MVC 1 and 2) as shown below. This will cause users to be routed to the controller and action defined in the MapRoute method if they navigate to your site’s base URL, i.e., yoursite.com will route the user to yoursite.com/foo/index:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Here I have created a custom "Default" route that will route users to the "YourAction" method within the "FooController" controller.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FooController", action = "Index", id = UrlParameter.Optional }
);
}
Step 1: Click on Global.asax File in your Solution.
Step 2: Then Go to Definition of
RouteConfig.RegisterRoutes(RouteTable.Routes);
Step 3: Change Controller Name and View Name
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Your Controller", action = "Your Action", id = UrlParameter.Optional }
);
}
}
Attribute Routing in MVC 5
Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.
A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Example",
url: "hey/now",
defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}
check RegisterRoutes method in global.asax.cs - it's the default place for route configuration...
I tried the answer but it didn't worked for me. This is what i ended up doing:
Create a new controller DefaultController. In index action, i wrote one line redirect:
return Redirect("~/Default.aspx")
In RouteConfig.cs, change controller="Default" for the route.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
If you don't want to change the router, just go to the HomeController
and change MyNewViewHere in the index like this:
public ActionResult Index()
{
return View("MyNewViewHere");
}

ASP.NET MVC 5 routing restriction

I've updated my code to use Area as suggested but the problem still exist. /dashboard is still available.
My Controllers folder has HomeController and AccountController. I have Areas/Admin/Controllers/DashboardController.cs
Problem:
My area admin controller can be accessed like this /admin/dashboard, but the problem is it can also be accessed using /dashboard -> this should show 404
here is my RouteConfig:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "project.Controllers" }
);
AdminAreaRegistration:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "project.Areas.Admin.Controllers" }
);
}
The /dashboard call is routed by the Default routing rule.
You can make the Default not to process the calls made to the dashboard controller by adding a constraint.
For example:
In the default routing rule you can add a constraint like the following:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "project.Controllers" },
constraints: new { controller = new Constraints.IsNotDashboard() }
);
Then, you can declare the constraint like this:
using System.Web;
using System.Web.Routing;
public class IsNotDashboard : IRouteConstraint
{
public IsNotDashboard()
{
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string controller = values["controller"].ToString().ToLower();
return controller != "dashboard";
}
}
With this constraint, all calls that match the dashboard controller will not be processed by the Default routing rule.
Thanks guys.
After searching the net, I finally found what works best for my problem.
The problem was that all controllers are being handled as well in Default route, so I just added controller constraints to Default. This way Default route will only accept request on specified controllers. Below is my new RouteConfig
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { controller = #"(Account|Manage|Home)" }
);

Controller with same name as an area - Asp.Net MVC4

I have a Contacts controller in the main/top area, and I have an area named "Contacts".
I get POST 404s to the Contacts controller if I register my areas before I register my top-level routes:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.DefaultBinder = new NullStringBinder();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
And, if I register my areas after my routes, my 404s to the Contacts controller goes away, but my routes to the Contacts area are now 404s.
...lots of duplicate controller name questions logged, but I haven't found a specific scenario where the area is the same name as the controller.
...probably an easy fix. Would appreciate help. :-D
fwiw, I am registering my Contacts area with an explicit namespace:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyMvcApplication.Controllers" }
);
}
There are two things to consider
In Application_Start() method register areas first AreaRegistration.RegisterAllAreas();.
In case of conflicting name, use the namespaces in RouteConfig.cs file of App_Start folder as well as all the routes defined in routes (like ContactsAreaRegistration.cs)
To replicate your scenario, I created a sample application and able to access successfully both URLs given below:
http://localhost:1200/Contacts/Index
http://localhost:1200/Contacts/contacts/Index
The structure of my application looks like:
Here inside ContactsAreaRegistration.cs file we are having following code:
public class ContactsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Contacts";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Contacts_default",
"Contacts/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcApplication1.Areas.Contacts.Controllers" }
);
}
}
Hope it will help you. If you need I can send sample application code which I have created. Thanks.
For MVC5, I did what #Snesh did but that didn't fully work. It would only resolve the controllers in my area but not in the root of the project if they had the same name. I wound up having to specify the namespaces as parameters in both the RegisterArea method and the RegisterRoutes method in my RouteConfig.cs.
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
// This resolves to the Controllers folder at the root of the web project
namespaces: new [] { typeof(Controllers.HomeController).Namespace }
);
}
AreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Handheld_default",
"Handheld/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
namespaces: new[] { typeof(Areas.Handheld.Controllers.HomeController).Namespace }
);
}

Default to Area Controller

For an ASP.NET MVC application, I have 2 controllers with the name Home. One of the controllers is in an Areas section, one is not. If someone goes to the base path /, I am trying to default to the controller in the Areas section. I am under the impression that this is possible. I have the following setup which I believe is supposed to make that happen -
When I go to /, I am still taken to the Controller in MVCArea01/Controllers/ and not MVCArea01/Areas/Admin/Controllers/.
(in case the code in the image is too small to see, here is the code for the method, RegisterRoutes)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new[] {"MVCAreas01.Areas.Admin.Controllers"} // I believe this code should cause "/" to go to the Areas section by default
);
}
What is the correct solution?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
area = "Admin"
}
}
#ABogus
I modified the AdminAreaRegistration.cs file. Refer the image below
Also I modified the Route.config as below.
I got the output as like this
You can download the sample project from https://www.dropbox.com/s/o8in2389e8aebak/SOMVC.zip
You should create additional route for your starting page, that will direct processing to the right controller:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home_Default",
"",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MVCAreas01.Areas.Admin.Controllers" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MVCAreas01.Controllers" }
);
}

Areas and routing

I'm quite stuck I might say dispite all other posts found on the site.
My solution has two areas Front and Back, and I don't want to use the default root controllers and views provided by default.
My FrontAreaRegistration.cs is like :
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Front",
"Front/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
, new[] { "Show.Areas.Front.Controllers" }
);
}
My BackAreaRegistration.cs is like :
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Back_default",
"Back/{controller}/{action}/{id}",
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional }
, new[] { "Show.Areas.Back.Controllers" }
);
}
And Global.asax like :
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Getting folowing exception :
Multiple types were found that match the controller named 'Home'. This
can happen if the route that services this request
('{controller}/{action}/{id}') does not specify namespaces to search
for a controller that matches the request. If this is the case,
register this route by calling an overload of the 'MapRoute' method
that takes a 'namespaces' parameter.
The request for 'Home' has found the following matching controllers:
Show.Areas.Front.Controllers.HomeController
Show.Areas.Back.Controllers.HomeController
Problem is I can't reach the Home controller from Front area. Even if correct namespace added to context.MapRoute method overload ...
Any help will be appreciated.
The error is raised because you don't specify Area name in your request. Because of that "Default" route (from Global.asax) is matched for request and tries to search "Index" action of "Home" controller. As far as there two matches (for both areas) exceptions is thrown.
There are few ways to fix this. One possible is to modify Global.asax:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new[] { "Show.Areas.Front.Controllers" }
).DataTokens.Add("Area", "Front");
But in this case "Default" route will work for Front area only.

Categories