How can i do like this url (http://www.domain.com/friendly-content-title) in Asp.Net MVC 4.
Note: This parameter is always dynamic. URL may be different: "friendly-content-title"
I try to Custom Attribute but I dont catch this (friendly-content-title) parameters in ActionResult.
Views:
- Home/Index
- Home/Video
ActionResult:
// GET: /Home/
public ActionResult Index()
{
return View(Latest);
}
// GET: /Home/Video
public ActionResult Video(string permalink)
{
var title = permalink;
return View();
}
RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Home Page",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Video Page",
url: "{Home}/{permalink}",
defaults: new { controller = "Home", action = "Video", permalink = "" }
);
}
What should I do for catch to url (/friendly-content-title)?
Radim Köhler's solution is a good one.
But another option if you want more control over routing is using a custom constraint.
Here's an example
RouteConfig.cs
So then on your home controller you could have action like this
HomeController.cs
The magic of this happens in the
IRouteConstraint
that we specified as the 4th argument in theMapRoute
call.PermaLinkRouteConstraint.cs
I just wanted to show a solution like this to show you can basically do anything you want.
Obviously this would need to be tweaked. Also you'd have to be careful not to have database calls or anything slow inside the
Match
method, as we set that to be called for every single request that comes through to your website (you could move it around to be called in different orders).I would go with Radim Köhler's solution if it works for you.
What we would need, is some marker keyword. To clearly say that the url should be treated as the dynamic one, with
friendly-content-title
. I would suggest to use the keywordvideo
, and then this would be the mapping of routes:Now, because
VideoPage
is declared as the first, all the urls (like these below) will be treated as the dynamic:while any other (
controllerName/ActionName
) will be processed standard wayTo enable attribute routing, call MapMvcAttributeRoutes during configuration. Following are the code snipped.
In MVC5, we can combine attribute routing with convention-based routing. Following are the code snipped.
It is very easy to make a URI parameter optional by adding a question mark to the route parameter. We can also specify a default value by using the form parameter=value. here is the full article.