I have sample .net core mvc application, im testing SEO friendly url creating , which is posted Here
I have created all the code as in the post.
My testing controller action is as follows
public IActionResult Index(int id, string titl)
{
//string titl = "";
var viewModel = new FriendlyUrlViewModel() { Id = 1, Name = "Detail home view." };
string friendlyTitle = FriendlyUrlHelper.GetFriendlyTitle(viewModel.Name);
// Compare the title with the friendly title.
if (!string.Equals(friendlyTitle, titl, StringComparison.Ordinal))
{
return RedirectToRoutePermanent("post_detail", new { id = viewModel.Id, title = friendlyTitle });
}
return View(viewModel);
}
and i have create custom route in startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "post_detail",
template: "FriendlyUrl/index/{id}/{title}"
).MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
when i navigate to
https://xxxxx:2222/FriendlyUrl/index/2/dfdsfdsfds
browser display nothing, I think issue is with custom routing, but i cant find it, can someone help on this?
Thanks.
You don't have to add:
routes.MapRoute(
name: "post_detail",
template: "FriendlyUrl/index/{id}/{title}")
That is for the global 'controller/action' map rule.
Instead, to map specified path to action, consider adding an attribute like this:
[Route("FriendlyUrl/index/{id}/{title}")]
public IActionResult Index([FromRoute]int id, [FromRoute]string title)
{
}
Simply add a name to your route. Like this:
[Route("FriendlyUrl/index/{id}/{title}", Name = "post_detail")]
public IActionResult Index([FromRoute]int id, [FromRoute]string title)
{
}
To route to this action from another controller or action, call it with:
// in action
return RedirectToRoute("post_detail");
// or
return RedirectToRoutePermanent("post_detail");
// I guess you don't have to lose the `Id`:
return RedirectToRoutePermanent("post_detail", new { id = 5 });
Simply add a ?
to the route template. Like this:
[Route("FriendlyUrl/index/{id}/{title?}", Name = "post_detail")]
public IActionResult Index([FromRoute]int id, [FromRoute]string title)
{
}