0
不工作
我的网站使用“使用的IPrincipal和IIdentity的登录表单登录身份 - 在HttpContext的
的代码可以看出below._iTs工作大
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
namespace FREELANCER.Models
{
public class UserPrincipal : IPrincipal
{
private LoginModel LoginInfo;
private DemoUsers d = new DemoUsers();
public UserPrincipal(LoginModel log)
{
LoginInfo = log;
Identity = new GenericIdentity(log.Emailaddress);
}
public IIdentity Identity
{
get;
private set;
}
public bool IsInRole(string role)
{
var roles = role.Split(new char[] { ',' });
return roles.Any(r => this.LoginInfo.Roles.Contains(r));
}
}
}
但我不能得到这个。工作:
string name = User.Identity.Name;
string AuthenticationType = User.Identity.AuthenticationType;
bool ss = User.Identity.IsAuthenticated;
bool Inrole =User.IsInRole("Admin");
他们时总是空的,为什么
这是真的,IPrincipa的对象? l和IIdentity将复制到HttpContext并因此可在整个网站上使用?
NB: namespace FREELANCER.Security
{
public class UserAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (String.IsNullOrEmpty(SessionPersister.UserName))
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "Login", Action = "Login" }));
else
{
DemoUsers ds = new DemoUsers();
UserPrincipal mp = new UserPrincipal(ds.FindUser(SessionPersister.UserName));
if (!mp.IsInRole(Roles))
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "AccessDenied", Action = "Index" }));
}
}
}
}
这是否意味着我必须在Logout中执行此操作: HttpContext.Current.User = null; Thread.CurrentPrincipal = null; ? – LalA
不,您不需要为注销指定null。默认情况下'HttpContext.Current.User'在每个请求上都是空的,直到你将Principal对象附加到它上面。 – Win