[英]How to access HttpContext.Current.User custom attributes in the view
I want to access some custom attributes in my view from a User
object. 我想从
User
对象访问视图中的一些自定义属性。 I am implementing custom attributes for authentication and I am changing the HttpContext.Current.User
inside of my global.asax. 我正在实现用于身份验证的自定义属性,并且正在我的global.asax中更改
HttpContext.Current.User
。
This is the User
class 这是
User
类
public class User : IPrincipal
{
...
public bool IsAdministrator => IsInRole(RolesConstants.GlobalAdministrator);
...
}
Here is where I am setting it in my Global.asax
这是我在
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;
}
As an example how can I do something like this? 例如,我该怎么做?
<button type="button" visible="@User.IsAdministrator" id="btn"></button>
Since the User
object is already accessible I don't want to pass in a Model
or use a string in the view such as @User.IsInRole("Admin")
由于
User
对象已经可以访问,因此我不想传递Model
或在视图中使用字符串,例如@User.IsInRole("Admin")
Edit: should I be making a custom type derive from IPrinciple
and explose the types like this? 编辑:我应该使自定义类型派生自
IPrinciple
并展开像这样的类型吗?
...
IIdentity Identity { get; }
bool IsInRole(string role);
bool IsAdministrator;
...
You need to cast the User
property to your custom class: 您需要将
User
属性强制转换为自定义类:
@{
var user = User as MyNamespace.User; // MyNamespace is the namespace of your User class
}
<button type="button" visible="@user.IsAdministrator" id="btn"></button>
[Edit] [编辑]
Another quick-and-dirty solution using an extension method: 另一个使用扩展方法的快捷解决方案:
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.