MVC에서 UserPrincipal 메서드를 확장하려고 시도했지만 작동하지 않는 이유를 알 수 없습니다.MVC에서 UserPrincipal을 확장하려고 시도하지 않았습니다.
내 코드 :
interface ICustomPrincipal : IPrincipal
{
Guid AuthId { get; set; }
Role UserRole { get; set; }
}
public class CustomPrincipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return false; }
public CustomPrincipal(string email)
{
this.Identity = new GenericIdentity(email);
}
public Guid AuthId { get; set; }
public Role UserRole { get; set; }
}
public class CustomPrincipalSerializeModel
{
public Guid AuthId { get; set; }
public Role UserRole { get; set; }
}
내 IdentityUser : 사용자가 그들이 권한 ID와 역할을 얻을 만든 그래서
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Guid UserIdMatch { get; set; }
public Role Role { get; set; }
}
.
사용자 로그인/등록 할 때 : 마지막에서
var user = db.Users.Include(i => i.Role).FirstOrDefault(i => i.UserName == model.Username);
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
serializeModel.AuthId = user.UserIdMatch;
serializeModel.UserRole = user.Role;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
user.UserName,
DateTime.Now,
DateTime.Now.AddDays(1),
false,
userData
);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
을 내 Global.asax
나는 다음과 같은 코드를 가지고 : 나는 @((User as CustomPrincipalSerializeModel).AuthId)
를 호출 할 때
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.AuthId = serializeModel.AuthId;
HttpContext.Current.User = newUser;
}
}
그것은 모든 내 눈에 괜찮을해야하지만를 아무 페이지에서나 다음 오류가 발생합니다.
Object reference not set to an instance of an object.
참고 : let sa y는 내가 로그인을 디버그. 나는 어떤 오류도 가지지 않고 쿠키가 올바른 데이터를 가지고 있음을 볼 수있다.
누군가가 문제의 원인을 지적 할 수 있습니까?
정확한 내용. 이제 AuthId가 작동합니다. 그러나 역할 속성은 어떤 생각도하지 못합니까? 신경 쓰지 마라. –