简体   繁体   中英

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. I am implementing custom attributes for authentication and I am changing the HttpContext.Current.User inside of my global.asax.

This is the User class

public class User : IPrincipal
{
    ...
    public bool IsAdministrator => IsInRole(RolesConstants.GlobalAdministrator);
    ...
}

Here is where I am setting it in my 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")

Edit: should I be making a custom type derive from IPrinciple and explose the types like this?

...
        IIdentity Identity { get; }
        bool IsInRole(string role);
        bool IsAdministrator;
...

You need to cast the User property to your custom class:

@{
    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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM