cos*_*ost 7 c# asp.net webforms .net-4.5
我一直在尝试自定义ASP.NET表单身份验证,让我困惑的是在哪里设置与用户关联的角色.阅读各种教程我已经看过建议使用Application_AuthenticateRequest或者FormsAuthentication_OnAuthenticate,代码的唯一区别在于如何userPrincipal分配给User.
Context.User = userPrincipal;
Run Code Online (Sandbox Code Playgroud)
和
e.User = userPrincipal;
Run Code Online (Sandbox Code Playgroud)
下面是每个完成的方法调用.这些功能是否相同,或者我应该注意哪些不同?
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(';');
GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
Context.User = userPrincipal;
}
}
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(';');
GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
e.User = userPrincipal;
}
}
Run Code Online (Sandbox Code Playgroud)
这些似乎是相同的,并且可能产生或多或少相同的结果.但是,存在一些关键差异,这些与Asp.net管道以及调用和触发各种事件的顺序有关.
当asp.net初始化时,它将FormsAuthentication_OnAuthenticate()处理程序挂钩到Application_AuthenticateRequest事件.因此,当AuthenticateRequest被调用时,它会遍历它的处理程序链并按顺序调用它们.
碰巧的是FormsAuthentication,asp.net为此配置的第一个模块是,这意味着FormsAuthentication_OnAuthenticate()将首先调用处理程序,然后是可以配置的任何自定义模块,最后是global.asax中配置的任何模块.
基本上,所有关于命令的命令都是关于.
所以问题的答案是,它们之间有什么区别......好吧,它们是两个不同的处理程序,在同一事件的身份验证管道中的不同点上调用.
在大多数情况下,你使用哪一个可能无关紧要,但在某些情况下它可能......例如,如果你在FormsAuthentication_OnAuthenticate()方法中完成了工作,链中的后续处理程序可能会覆盖你用它做的事情.自己的设置.
| 归档时间: |
|
| 查看次数: |
4371 次 |
| 最近记录: |