【发布时间】:2016-01-31 16:19:54
【问题描述】:
我想改一下
localhosht:3220/MyController/MyAction?id=1
到这里
localhosht:3220/myText/MyController/MyAction?id=1
这样它可以随时工作,即使在重定向、路由或其他情况下。
谢谢。
【问题讨论】:
标签: c# asp.net asp.net-mvc routing
我想改一下
localhosht:3220/MyController/MyAction?id=1
到这里
localhosht:3220/myText/MyController/MyAction?id=1
这样它可以随时工作,即使在重定向、路由或其他情况下。
谢谢。
【问题讨论】:
标签: c# asp.net asp.net-mvc routing
只需将文本添加到路由 url:
routes.MapRoute(
name: "Default",
url: "myText/{controller}/{action}"
);
【讨论】:
您可以使用自定义route 来匹配您想要的uri。在RouteConfig的RegisterRoutes方法中,添加以下内容。
这里的顺序很重要,如果在“MyText”路由前加上“Default”路由,那么MyText路由不会被命中。
//for your custom route that starts with "myText"
routes.MapRoute(
name: "MyText",
url: "myText/{controller}/{action}/{id}",
defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional }
);
//for other normal routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
【讨论】:
虽然添加带有myText/{controller}/{action}/{id} 的url 参数的路由(高于您的默认路由)肯定会起作用,如果您打算经常使用myText,您可能还想要来看看areas的概念。
默认情况下,在您的Global.asax 中,在您的Application_Start() 函数中,您会调用该方法:
AreaRegistration.RegisterAllAreas();
这样做的目的是在您的项目中寻找一个特殊的Areas 文件夹,并在其下注册每个具有从AreaRegistration 扩展的类并覆盖RegisterArea 函数的文件夹。类似于你的RouteConfig.cs,这个类可以是这样的:
public class MyTextAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "MyText";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "MyText_default",
url: "MyText/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
注意:您可以通过脚手架在您的 MVC 项目中创建区域:只需右键单击您的项目和 Add.. -> Area。一切都会自动为您完成。
最后,Areas 为您的MyText/SomeController/SomeAction 需求提供了更持久的解决方案。详细文章可以查看this。
【讨论】:
routes.MapRoute(
name: "Default",
url: "{myText}/{controller}/{action}/{id}"
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
myText= UrlParameter.Optional
);
如果你想使用像 myText 这样的参数来使你的 Url Seo 友好,它会为你工作。
【讨论】: