重定向在asp.net mvc 2控制器初始化例程

时间:2015-05-08 12:46:57

标签: c# asp.net asp.net-mvc

如果会话变为null,我需要从任何控制器重定向到登录页面,我试过这个但是它不起作用

protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
    base.Initialize(requestContext);
    if (Session["FirstName"] == null) {
        ret.msg = Resources.Resources.error_session_expired;
        ret.status = "danger";
        RedirectToAction("LogIn", "Account", new {
            area = ""
        }); // <-- i added a return in front of this, but it was red underlined
    }
}

最好的方法是什么

1 个答案:

答案 0 :(得分:1)

使用动作过滤器:

public class RedirectIfNullSessionAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    if (filterContext.HttpContext.Session["FirstName"] == null) 
    {
      filterContext.Result = new RedirectToRouteResult(
        new RouteValueDictionary 
          { 
            { "controller", "Account" }, 
            { "action", "Login" } 
          });
    }
  }
}

然后将其应用于您的控制器:

[RedirectIfNullSession]
public class MyController : Controller
{
  ....