Search code examples
c#asp.net-mvcroutesurl-routingasp.net-mvc-routing

Route URL must be started with '/'


I've declared Index action in Home controller:

[HttpGet]
public ActionResult Index(string type)
{
   if (string.IsNullOrEmpty(type))
   {
      return RedirectToAction("Index", new { type = "promotion" });
   }
   return View();
}

That accepts:

https://localhost:44300/home/index?type=promotion

and

https://localhost:44300/?type=promotion

Everything was ok until I config route for 404 page:

    routes.MapRoute(
        name: "homepage",
        url: "home/index",
        defaults: new { controller = "Home", action = "Index" }
    );
    routes.MapRoute(
        name: "default",
        url: "/",
        defaults: new { controller = "Home", action = "Index" }
    );
    routes.MapRoute(
        "404-PageNotFound",
        "{*url}",
        new { controller = "Error", action = "PageNotFound" }
    );

Invalid syntax:

The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.

If I remove the second configuration,

https://localhost:44300/?type=promotion

wouldn't be accepted. -> Show 404 page.

My question is: Is there a way to config route URL start with '/' (none controller, none action)?


Solution

  • Your route is misconfigured, as the error states it cannot begin with a /, and for the home page it doesn't need to. In that case it should be an empty string.

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

    However, it is a bit unusual (and not SEO friendly) to want to map more than one route to the home page of the site as you are doing.

    It is also unusual to do a redirect to a home page, which does an additional round trip across the network. Usually routing directly to the page you want will suffice without this unnecessary round trip.

    routes.MapRoute(
        name: "homepage",
        url: "home/index",
        defaults: new { controller = "Home", action = "Index", type = "promotion" }
    );
    routes.MapRoute(
        name: "default",
        url: "/",
        defaults: new { controller = "Home", action = "Index", type = "promotion" }
    );
    
    // and your action...
    [HttpGet]
    public ActionResult Index(string type)
    {
       return View();
    }