我有示例.net核心mvc应用程序,正在测试SEO友好的url创建, 已发布Here
我已经创建了帖子中的所有代码。
我的测试控制器动作如下
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);
}
我已经在startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "post_detail",
template: "FriendlyUrl/index/{id}/{title}"
).MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
当我导航到
https://xxxxx:2222/FriendlyUrl/index/2/dfdsfdsfds
浏览器什么也不显示, 我认为问题在于自定义路由,但我找不到它, 有人可以帮忙吗?
谢谢。
答案 0 :(得分:2)
您不必添加:
routes.MapRoute(
name: "post_detail",
template: "FriendlyUrl/index/{id}/{title}")
这是针对全局“控制器/动作”映射规则的。
相反,要映射指定的路径到操作,请考虑添加这样的属性:
[Route("FriendlyUrl/index/{id}/{title}")]
public IActionResult Index([FromRoute]int id, [FromRoute]string title)
{
}
只需在路线中添加一个名称即可。像这样:
[Route("FriendlyUrl/index/{id}/{title}", Name = "post_detail")]
public IActionResult Index([FromRoute]int id, [FromRoute]string title)
{
}
要从另一个控制器或动作路由至此动作,请使用以下命令进行调用:
// 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 });
只需将?
添加到路由模板。像这样:
[Route("FriendlyUrl/index/{id}/{title?}", Name = "post_detail")]
public IActionResult Index([FromRoute]int id, [FromRoute]string title)
{
}