问题
I am trying to set the root path of my domain http://www.example.com/ to the PersonSearch
controller using the Routing module, but it doesn't seem to be having any effect (404 error).
The URL http://www.example.com/person/search correctly takes me to the desired page.
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
"Root",
"",
defaults: new { controller = "Person", action = "Search" }
);
}
}
PersonController.cs
public class PesonController : Controller
{
[HttpGet]
[Route("person/search")]
public ActionResult Search()
{
PersonSearchViewModel psvm = new PersonSearchViewModel();
return View(psvm);
}
}
回答1:
I think it's missing the url parameter in your route
routes.MapRoute(
"Root",
url: "{controller}/{action}",
defaults: new { controller = "Person", action = "Search" }
);
回答2:
This is an ordering problem. If you define a URL as empty string (root), the route should be placed before all of your other routes.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Root",
"",
defaults: new { controller = "Person", action = "Search" }
);
routes.MapMvcAttributeRoutes();
// Place any other `MapRoute` declarations here
}
}
回答3:
I found out that I could achieve what I wanted with a simple Attribute Routing piece of code.
public class PesonController : Controller
{
[HttpGet]
[Route("~/")]
[Route("person/search")]
public ActionResult Search()
{
PersonSearchViewModel psvm = new PersonSearchViewModel();
return View(psvm);
}
}
I can then remove the call to routes.MapRoute()
in RouteConfig
来源:https://stackoverflow.com/questions/32649459/trying-to-setup-root-homepage-using-routing