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

前端 未结 6 1380
失恋的感觉
失恋的感觉 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:17

    The best way to make your IPrincipal implementation accessible in your Razor pages using ASP.NET MVC, is doing the following:

    1. Implement the System.Security.Principal.IPrincipal interface.
    2. Implement the System.Security.Principal.IIdentity interface.
    3. In Global.asax define a method for: void Application_AuthenticateRequest(Object, EventArgs) that persists your both implementations of IPrincipal and IIdentity.
    4. Create an extension method for IPrincipal to expose your implementation of IIdentity.
    5. Finally, add the namespace for the previous extension method in your web.config file in .

    At the end, you will be able to access your custom implementation of IIdentity instead of type casting. You now can access your custom implementation like this:

    Hello @User.CustomIdentity().FirstName @User.CustomerIdentity().LastName!
    

    These steps are a concise and brief description of a well detailed article written here: http://rizzo7.blogspot.com/2012/04/mvc-30-razor-custom-principal-and.html

提交回复
热议问题