在MVC VIEW中使用@ User.IsInRole(“Admin”)

时间:2013-11-27 17:46:27

标签: asp.net-mvc

我在mvc4中使用@ User.IsInRole(“Admin”)  当我在global.asax中使用此命令时它返回true但是当我在mvc中使用时它返回sql server连接错误。

1 个答案:

答案 0 :(得分:0)

protected void Application_AuthenticateRequest(Object sender,EventArgs e)         {             if(Context.User == null)                 返回;

        var userService = ObjectFactory.GetInstance<IUserService>();

        UserStatus userStatus = userService.GetStatus(Context.User.Identity.Name);

        if (userStatus.IsBaned)
            FormsAuthentication.SignOut();

        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || authCookie.Value == "")
            return;

        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);


        // retrieve roles from UserData
        if (authTicket == null) return;
        string[] roles = authTicket.UserData.Split(',');

        if (userStatus.Role != roles[0])
            FormsAuthentication.SignOut();

        Context.User = new GenericPrincipal(Context.User.Identity, roles);

    }