How can I make accessing my custom IPrincipal easier in ASP.NET MVC?

前端 未结 6 1227
失恋的感觉
失恋的感觉 2021-02-14 23:18

I\'ve written a custom principal object which contains a few additional fields (email and userid in addition to the username).

In order to access these properties I have

6条回答
  •  不知归路
    2021-02-15 00:12

    You could either create a base class and override the "User" property using the "new" keyword or create an extension method like this:

    public static class ControllerExtensions
    {
        public static CustomPrincipal CustomPrincipal(this Controller controller)
        {
            if(controller.User is CustomPrincipal)
            {
                return controller.User as CustomPrincipal;
            }
            return null; // maybe return an empty object instead to get around null reference...
        }
    }
    

提交回复
热议问题