会话在mvc4

时间:2015-09-09 12:46:19

标签: asp.net-mvc-4 authentication

我正在使用过滤器来检查用户是否经过身份验证。如果不需要重定向到登录页面。

public class CookieAuthorizeAttribute : AuthorizeAttribute
{
 protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (authorized)
        {
            FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
            System.Web.Security.FormsAuthentication.RenewTicketIfOld(identity.Ticket);

            return true;
        }
        else
        {
            httpContext.Items["redirectToCompleteProfile"] = true;

            return false;
        }

    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile"))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "Login",
                action = "Login",
            });
            filterContext.Result = new RedirectToRouteResult(routeValues);
        }

   }


}

}

即使代码正在进入Login控制器,重定向也不起作用。 请求来自javascript。

1 个答案:

答案 0 :(得分:0)

在ajax调用案例中,重定向不起作用,它只会返回Login View html作为ajax调用的响应。

你必须检查它是否是一个ajax请求返回状态和应该以JSON格式重定向的url:

if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile") && !context.HttpContext.Request.IsAjaxRequest())
{
    var routeValues = new RouteValueDictionary(new
    {
        controller = "Login",
        action = "Login",
    });
    filterContext.Result = new RedirectToRouteResult(routeValues);
}
else
{
   filterContext.HttpContext.Response.StatusCode = 403;
   filterContext.Result = new JsonResult 
                              { 

                                  Data = "LogOut",
                                  JsonRequestBehavior = JsonRequestBehavior.AllowGet 
                              };
}

在您的主布局中,您可以写:

$(document).ajaxError(function(e, xhr, opts) {

            console.log(xhr.status);
            if (xhr.status == 403 && && xhr.responseText.indexOf("LogOut") != -1) {

                window.location.href = "@Url.Action("Login", "Login")";
            }

        });