![](/img/trans.png)
[英]How to get HttpContext.Current.User as custom principal in mvc c#
[英]How to access HttpContext.Current.User custom attributes in the view
我想从User
对象访问视图中的一些自定义属性。 我正在实现用于身份验证的自定义属性,并且正在我的global.asax中更改HttpContext.Current.User
。
这是User
类
public class User : IPrincipal
{
...
public bool IsAdministrator => IsInRole(RolesConstants.GlobalAdministrator);
...
}
这是我在Global.asax
设置的地方
protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
{
...
var winUser = new User
{
EMail = user.Person.Email,
FirstName = user.Person.FirstName,
LastName = user.Person.LastName,
Identity = wi,
NetworkAccountName = user.UserName,
UserId = user.UserName,
Roles = userRoles,
};
HttpContext.Current.User = winUser;
}
例如,我该怎么做?
<button type="button" visible="@User.IsAdministrator" id="btn"></button>
由于User
对象已经可以访问,因此我不想传递Model
或在视图中使用字符串,例如@User.IsInRole("Admin")
编辑:我应该使自定义类型派生自IPrinciple
并展开像这样的类型吗?
...
IIdentity Identity { get; }
bool IsInRole(string role);
bool IsAdministrator;
...
您需要将User
属性强制转换为自定义类:
@{
var user = User as MyNamespace.User; // MyNamespace is the namespace of your User class
}
<button type="button" visible="@user.IsAdministrator" id="btn"></button>
[编辑]
另一个使用扩展方法的快捷解决方案:
public static class ViewUserExtensions {
public static User ToCustom(this IPrincipal principal)
{
return principal as User;
}
}
<button type="button" visible="@User.ToCustom().IsAdministrator" id="btn"></button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.