我认为你正在寻找的就是原因T4MVC http://t4mvc.codeplex.com/存在 - 它删除了与控制器和操作相关的所有“魔术字符串”,并将它们替换为类和属性。
使用 T4MVC,这
if (!Request.IsAuthenticated)
return RedirectToAction("Login", "Account");
变成这个
if (!Request.IsAuthenticated)
return RedirectToAction(MVC.Account.Login());
可以在 T4MVC 设置中设置一个标志,以强制它在每个构建上运行模板,从而在某些内容可能发生更改时向您发出早期警告。
虽然不是您所要求的,但您可以考虑使用AuthorizeAttribute http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx无需检查请求是否在控制器操作内经过身份验证。
this
public class HomeController : Controller
{
public ActionResult Index()
{
if (!Request.IsAuthenticated)
return RedirectToAction("Login", "Account");
// .... carry on
}
}
becomes
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
// .... carry on
}
}
then in web.config
,设置url指向账户登录URL
<authentication mode="Forms">
<forms loginUrl="account/login" timeout="30" />
</authentication>
当然,如果您的控制器和操作发生变化(类似于您最初的投诉),这不会给您带来任何安全,但您始终可以设置一个路由,将所选的 URL 定向到正确的控制器和操作,并使用 T4MVC 生成的类路线,如果情况发生变化,会向您提供一些编译时警告。