问题:
I need to do something fairly simple: in my ASP.NET MVC application, I want to set a custom IIdentity / IPrincipal. 我需要做一些相当简单的事情:在我的ASP.NET MVC应用程序中,我想设置一个自定义IIdentity / IPrincipal。 Whichever is easier / more suitable. 哪个更容易/更合适。 I want to extend the default so that I can call something like User.Identity.Id
and User.Identity.Role
. 我想扩展默认值,以便我可以调用User.Identity.Id
和User.Identity.Role
类的东西。 Nothing fancy, just some extra properties. 没什么特别的,只是一些额外的属性。
I've read tons of articles and questions but I feel like I'm making it harder than it actually is. 我已经阅读了大量的文章和问题,但我觉得我做得比实际更难。 I thought it would be easy. 我觉得这很容易。 If a user logs on, I want to set a custom IIdentity. 如果用户登录,我想设置自定义IIdentity。 So I thought, I will implement Application_PostAuthenticateRequest
in my global.asax. 所以我想,我将在我的global.asax中实现Application_PostAuthenticateRequest
。 However, that is called on every request, and I don't want to do a call to the database on every request which would request all the data from the database and put in a custom IPrincipal object. 但是,每次请求都会调用它,并且我不希望在每个请求上调用数据库,这些请求将从数据库请求所有数据并放入自定义IPrincipal对象。 That also seems very unnecessary, slow, and in the wrong place (doing database calls there) but I could be wrong. 这似乎也是非常不必要,缓慢,并且在错误的地方(在那里进行数据库调用)但我可能是错的。 Or where else would that data come from? 或者数据来自何处?
So I thought, whenever a user logs in, I can add some necessary variables in my session, which I add to the custom IIdentity in the Application_PostAuthenticateRequest
event handler. 所以我想,每当用户登录时,我都可以在我的会话中添加一些必要的变量,我将其添加到Application_PostAuthenticateRequest
事件处理程序中的自定义IIdentity中。 However, my Context.Session
is null
there, so that is also not the way to go. 但是,我的Context.Session
在那里是null
,所以这也不是要走的路。
I've been working on this for a day now and I feel I'm missing something. 我已经在这一天工作了一天,我觉得我错过了什么。 This shouldn't be too hard to do, right? 这不应该太难,对吧? I'm also a bit confused by all the (semi)related stuff that comes with this. 我也对此附带的所有(半)相关内容感到困惑。 MembershipProvider
, MembershipUser
, RoleProvider
, ProfileProvider
, IPrincipal
, IIdentity
, FormsAuthentication
.... Am I the only one who finds all this very confusing? MembershipProvider
, MembershipUser
, RoleProvider
, ProfileProvider
, IPrincipal
, IIdentity
, FormsAuthentication
....我是唯一一个发现这一切令人困惑的人吗?
If someone could tell me a simple, elegant, and efficient solution to store some extra data on a IIdentity without all the extra fuzz.. that would be great! 如果有人能告诉我一个简单,优雅,高效的解决方案,可以在IIdentity上存储一些额外的数据而不需要额外的模糊...这将是非常棒的! I know there are similar questions on SO but if the answer I need is in there, I must've overlooked. 我知道在SO上有类似的问题,但如果我需要的答案就在那里,我一定会忽略。
解决方案:
参考一: https://stackoom.com/question/4Srf/ASP-NET-MVC-设置自定义IIdentity或IPrincipal参考二: https://oldbug.net/q/4Srf/ASP-NET-MVC-Set-custom-IIdentity-or-IPrincipal
来源:oschina
链接:https://my.oschina.net/u/4438370/blog/4269769