问题描述
这是我的的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:
当安全模块已发生 建立用户的身份。
...
该PostAuthenticateRequest事件 在的AuthenticateRequest之后引发 已经发生的事件。功能, 预订了 PostAuthenticateRequest事件可以 访问是受处理的任何数据 该PostAuthenticateRequest。
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页生命周期。
但由于你的问题被打上了ASP.NET MVC我会强烈建议您在执行这个到自定义 [授权]
属性使用此事件,而不是。例如:
But because your question is tagged with ASP.NET MVC I would strongly recommend you performing this into a custom [Authorize]
attribute instead of using this event. Example:
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]
属性装饰你的控制器/动作:
Now decorate your controllers/actions with the [MyAuthorize]
attribute:
[MyAuthorize]
public ActionResult Foo()
{
// if you got here the User property will be the custom
// principal you injected in the authorize attribute
...
}
这篇关于当`PostAuthenticateRequest`得到执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!