本文介绍了在ASP.NET MVC中通过Slug进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个控制器操作,如下所示:
I have a controller action as you can see below:
public ActionResult Content(string slug)
{
var content = contentRepository.GetBySlug(slug);
return View(content);
}
我希望将此类网址发送给我的操作:
I want this kind of urls to be routed to my action:
这是我的RegisterRoutes方法:
Here is my RegisterRoutes method:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Page", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "GetContent",
url: "{slug}",
defaults: new { controller = "Page", action = "Content", slug = "" }
);
}
但是它不起作用,我在做什么错了?
But it does not work, what am I doing wrong?
谢谢
推荐答案
1将子弹路线置于默认路线上方,如果没有,它永远不会走路径
2不能为空,如果为空,则URL为必须使用默认路由
1 put the slug route above default route,if not ,it never go the slug route
2 you slug can not be empty,if empty ,the url will be http://localhost/ it must go default route
routes.MapRoute(
name: "slug",
url: "{slug}",
defaults: new { controller = "Home", action = "show" },
constraints: new{ slug=".+"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
我想不要选择 Content作为动作名称,因为其中有一个Content Method基类
and i think don't pick "Content" as action name,becuse there is a Content Method in base class
这篇关于在ASP.NET MVC中通过Slug进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!