Trying to setup root homepage using routing

北城余情 提交于 2019-12-13 05:23:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!