MVC Routing Issue when trying www.example.com/id

Let say I have a website www.example.com

the default routing looks like

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);

Ok that works fine but lets say I want my site when I go to www.example.com/id to go to www.example.com/login/index/id

How would I configure/add routing for this, with out breaking my other pages where I am actually trying to go to www.example.com/controller ?

EDIT: Unfortunately id is a string so I do not have any concrete constraints that I can think of that would work. Think of maybe instead of id I should have said companyname or sitename so the url would look like www.example.com/companyname .

The only solution that I have come up with so far is adding a maproute for each one of my controllers like this

routes.MapRoute( name: "Home", url: "Home/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

routes.MapRoute( name: "Settings", url: "Settings/{action}/{id}", defaults: new { controller = "Settings", action = "Index", id = UrlParameter.Optional } );

routes.MapRoute( name: "companyname", url: "{id}", defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional } );

routes.MapRoute( name: "default", url: "{controller}/{action}/{id}", defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional } );

This will work but I have many controllers and if I add one in the future and forget to adjust the routes it will fail. Also this is unlikely but if a companyname happens to the be same as one of my controller names it would also fail.


在控制器中,您可能会重定向到另一个控制器/操作:

public ActionResult yourAction()
{
  return  RedirectToAction("nameAction","nameController");
}

Did you tried adding this mapping first:

routes.MapRoute( name: "Custom", url: "{id}", defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional } );

That should work but keep in mind that routes are evaluated secuentially, so you will have to organize mappings in order to reach out all pages in your site.

For example, routes like www.example.com/Product could be redirected to /Login by mistake.

EDIT: You can add constraints, so if id is an int value, you can try with the following:

 routes.MapRoute("Custom", "{id}",
                new { controller = "Login", action = "Index" },
                new { id = @"d+" }

EDIT 2: Having ids as string values, the only solution I see is to manually add each controller as you said, or to add something like this:

routes.MapRoute(
name: "Default",
url: "app/{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }

);

This way you don't need to update each route in the future.

链接地址: http://www.djcxy.com/p/36766.html

上一篇: 默认区域路线在mvc中不起作用5

下一篇: 尝试www.example.com/id时MVC路由问题