问题
I want the user to be routed to the web site home page (\Home) if they access the area root url directly (\Products). What is the correct coding in the RegisterArea route.map?
Here is the folder structure in the project and how they map to the web site
/Area/Products -> /Products
/View/Home - > /Home
If users goes to / , then go to /Home (use the index action for controller Home)
If users goes to /Products , then go to /Home (use the index action for controller Home)
If users goes to /Products/Fruit , then use the index action for controller Fruit; /Products/Fruit
I have a standard 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 }
);
}
I have a standard entries in the global.asax.cs file
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Here is my updated area registration route
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Product_default",
"Product/{controller}/{action}/{id}",
new {
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional });
}
If I go to \Products , I get error message
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /products/
Two possible solutions, which some might consider at hack are:
create a controller in the area, assign the default to that controller and redirect the index action back to the home controller
register 301 redirect for /products in the Global.asax.cs file
回答1:
The ProductAreaRegistration was configured to default to a controller that would redirect to the Home controller on the web site root (area="").
The ProductAreaRegistration
public class ProductAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Product";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Product_default",
"Product/{controller}/{action}/{id}",
defaults: new { controller="Redirect", action = "Index", id = UrlParameter.Optional });
}
}
The Controller
public class RedirectController : Controller
{
// GET: Product/Redirect
public ActionResult Index()
{
return RedirectToAction("Index","Home",new { area = "" });
}
}
来源:https://stackoverflow.com/questions/26160881/how-to-code-maproute-in-registerarea-to-route-the-area-default-to-another-area