[英]How to access HttpContext.Current.User custom attributes in the view
[英]How to get HttpContext.Current.User as custom principal in mvc c#
我正在尝试将HttpContext.Current.User
与我自己的继承自IPrincipal
的类一起使用。 我不确定为什么..
var lIdentity = new UserIdentity(lFormsTicket);
var lRoles = lAuthUser.Roles.Select(x => x.Role.ToString()).ToArray();
var lPrincipal = new GenericPrincipal(lIdentity, lRoles);
System.Web.HttpContext.Current.User = lIdentity;
我设置它之后就可以了。 但是,如果我在网站上做了另一个请求,它说它无法投射它。 我在这里错过了什么吗?
当它应该是IPrincipal
时,你将User
设置为IIdentity
var lIdentity = new UserIdentity(lFormsTicket);
var lRoles = lAuthUser.Roles.Select(x => x.Role.ToString()).ToArray();
var lPrincipal = new GenericPrincipal(lIdentity, lRoles);
System.Web.HttpContext.Current.User = lPrincipal;
您可能需要使用自己的自定义IPrincipal
public class UserPrincipal : IPrincipal {
string[] roles;
public UserPrincipal (IIdentity identity, param string[] roles) {
this.Identity = identity;
this.roles = roles ?? new string[]{ };
}
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) {
return roles.Any(s => s == role);
}
}
我不确定该应用程序是否会抱怨,因为它可能期望一个ClaimsPrincipal
派生类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.