gpt4 book ai didi

c# - `PostAuthenticateRequest` 什么时候执行?

转载 作者:可可西里 更新时间:2023-11-01 08:03:18 24 4
gpt4 key购买 nike

这是我的 Global.asax.cs 文件:

public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
...
}

protected void Application_Start()
{
this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
}

// This method never called by requests...
protected void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { });
Context.User = principal;
}
}
}

PostAuthenticateRequest 何时执行?

最佳答案

根据documentation :

Occurs when a security module has established the identity of the user.

...

The PostAuthenticateRequest event is raised after the AuthenticateRequest event has occurred. Functionality that subscribes to the PostAuthenticateRequest event can access any data that is processed by the PostAuthenticateRequest.

这是 ASP.NET Page Life Cycle .

但是因为您的问题是用 ASP.NET MVC 标记的,所以我强烈建议您在自定义 [Authorize] 属性中执行此操作,而不是使用此事件。示例:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { });
httpContext.User = principal;
}
}
return isAuthorized;
}
}

现在用 [MyAuthorize] 属性装饰你的 Controller / Action :

[MyAuthorize]
public ActionResult Foo()
{
// if you got here the User property will be the custom
// principal you injected in the authorize attribute
...
}

关于c# - `PostAuthenticateRequest` 什么时候执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5947278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com