I want to create simple blog engine. For fancy and clean url I'd like to use routing mechanism implemented in MVC4.
I added to RouteConfig.cs this lines:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ArticleList",
url: "Articles/{category}/{page}",
defaults: new
{
controller = "Articles",
category = UrlParameter.Optional,
page = 1
});
}
}
And if I write in web browser url:
http://localhost:6666/Articles/SomeCategory/3
I want to move to this controller:
public class ArticlesController : ControllerBase<IHomeService>
{
public ActionResult Index(string category, int page = 0)
{
return View("~/Views/Article/Articles.cshtml");
}
}
with parameters category = "SomeCategory" and page = 1.
All I recieve is Server Error in '/' Application. The resource cannot be found.
What is wrong?
routes.MapRoute(
name: "ArticleList",
url: "{controller}/{category}/{page}",
defaults: new
{
category = UrlParameter.Optional,
page = 1,
action = "Index"
},
constraints: new
{
controller = "Articles"
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
EDIT
I should have added this to the answer but I was in a hurry:
In the example above using the constraints or hard-coding the route produces the same result. Constraints are more flexible because you can use regex to restrict the controllers/actions/parameters values that your route is for. For instance, if you add a new route that uses the /category/page pattern your can then modify the controller constraint accordingly:
constraints: new { controller = @"^(Articles|AnotherController)$" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With