您可以使用attribute routing更容易。
你RouteConfig看起来象下面这样:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // enable attribute routing
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
}
然后你就可以添加动作象下面这样:
public class SponsorsController : Controller
{
[Route("sponsors/information")]
public ActionResult RedirectInformation()
{
return RedirectPermanent("http://yoururl.com");
}
}
编辑一个
如果你不希望使用属性的路由,你仍然会需要的操作,但你RouteConfig看起来象下面这样:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//The order is important here
routes.MapRoute(
name: "redirectRoute",
url: "sponsors/information",
defaults: new { controller = "Home", action = "RedirectToInformation"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
路由就是这样,如果找到匹配的路由的其余部分被忽略。所以,你想要把顶部和最普遍最具体的路线在底部
编辑两个(基于评论)
你可以把一个简单的AppSettings在Web.config中象下面这样:
<appSettings>
<add key="UseAttributeRouting" value="true" />
</appSettings>
然后在RegisterRoutes
你可以像下面阅读并做出决定。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAttributeRouting"]))
{
routes.MapMvcAttributeRoutes();
}
else
{
routes.MapRoute(
name: "redirectRoute",
url: "sponsors/information",
defaults: new {controller = "Home", action = "RedirectToInformation"}
);
}
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
浏览器有时缓存这些重定向,所以你可能要建议您清除浏览器缓存,如果你更改这些设置。请检查此superuser post以清除Chrome的缓存。
非常感谢您!属性路由可能是我最好的选择。我在文章中没有提到的一件事是,我希望能够通过web.config应用程序设置关闭重定向功能。如果我使用属性路由,我可以通过有条件地包含路由来关闭它.MapMvcAttributeRoutes();在我的代码路径?这个网站运行一个孤儿院赞助计划,我所有的时间都被捐赠。感谢您给予您的时间和专业知识! –
@TracyFletcher欢迎您! :)这真是太棒了,你正在捐出时间,我很乐意帮忙。请检查我的编辑。 – Yogiraj
谢谢,我很欣赏客气的话,以及帮助。是的,你的编辑正是我所想的。最后一个问题是,我可以在单个控制器操作上使用多个属性吗? –