Short urls containing product categories like
http://example.com/Computers
Should used in ASP.NET MVC 4 shopping cart. If there is no controller, Home Index method with id parameter as Computers should called.
I tried to add id parameter to home controller using
public class HomeController : MyControllerBase
{
public ActionResult Index(string id)
{
if (!string.IsNullOrWhiteSpace(id))
{
return RedirectToAction("Browse", "Store", new
{
id = id,
});
}
return View("Index", new HomeIndexViewModel());
}
but http://example.com/Computers causes 404 error
Server Error in '/' Application.
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: /Computers
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1073.0
How to force some controller call if there is no controller defined after slash in http://example.com/....
MVC default routing is used:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
It looks like MVC ignores routing parameter:
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Howe to fix this ?
your problem is because aspnet mvc is trying to find a controller with the name Computers, and your controller is Home, you can add a new route like this before the route with name Default:
routes.MapRoute(
name: "Computers",
url: "Computers",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
In the above case, you are creating a route with match with the url http://domain.com/Computers and this route will be manage by the HomeController.
Also, according to your comment, you can have a route like:
routes.MapRoute(
name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);