2012-07-30 48 views
2

添加了一个AuthorizeImage事件处理程序来映像访问限制。当我试图检查用户名和身份验证状态时注意到以下几点:图像Resizer在事件处理程序中的User.Identity

下面不会导致异常,但似乎会破坏它。无论是否验证,都会显示未找到图像的默认图标。 测试this.User =相同的结果。 HttpContext.Current.User =相同的结果

Config.Current.Pipeline.AuthorizeImage += delegate(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e) 
{ 
    if (context.User.Identity.IsAuthenticated) { context.Response.Redirect("http://db2.stb00.s-msn.com/i/AF/263B63C5E656379CEE93E7A8692EC7.gif"); }  
}; 

下面的工作就好了(this.User和HttpCOntext.Current.User以及)

Config.Current.Pipeline.AuthorizeImage += delegate(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e) 
{ 
    context.Response.Redirect("http://db2.stb00.s-msn.com/i/AF/263B63C5E656379CEE93E7A8692EC7.gif"); 
}; 

这总是重定向

Config.Current.Pipeline.AuthorizeImage += delegate(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e) 
{ 
    if (context.User == null) 
     context.Response.Redirect("http://db2.stb00.s-msn.com/i/AF/263B63C5E656379CEE93E7A8692EC7.gif"); 
}; 

我开始在Application_Start中测试,但实际上也尝试了Application_PostAuthenticateRequest。虽然结果相同。我通过自定义代码进行身份验证,但使用标准formsatuhentication来设置cookie。 [Authorize]在应用程序中正常工作。任何可能在这里出错的建议?

+0

请,如果你得到了“未找到'图标,直接打开URL并获取实际的错误信息。 – 2012-07-30 22:46:17

+0

抱歉应该补充一点。我只收到nullreference异常,“对象引用未设置为对象的实例”。标记包含“if(context.User.Identity.IsAuthenticated){context.Response.Redirect(”http://db2.stb00.s-msn.com/i/AF/263B63C5E656379CEE93E7A8692EC7.gif“);}”的行。 所以context.User没有实例化它似乎。问题是为什么。由于身份验证在其他方面工作(和@ User.Identity.Name在视图中给我的用户名)我怀疑有关事件处理程序的东西? – Baserz 2012-07-30 22:57:28

+0

ASP.NET不会为匿名用户填充context.User。如果您不是匿名的,那么您的代码在PostAuthorize之前不会加载用户,这是一个错误。 – 2012-07-30 23:04:01

回答

4

您的服务器被配置为仅对某些请求扩展(如.aspx,.ashx等)运行FormsAuthenticationModule。有两种方法可以解决此问题。

  1. 拆下并在<system.webServer> <modules>重新添加FormsAuthenticationModule(用于集成模式),滴前提= “managedHandler” 属性:
  2. 启用RAMMFAR(runAllManagedModulesForAllRequests)

此信息包含有关更多细节执行#1和#2:

How do I protect static files with ASP.NET form authentication on IIS 7.5?

+0

解决方案1似乎解决了这个问题,感谢您的帮助。 – Baserz 2012-07-31 15:52:15

+0

解决方案1是可行的方法。有关RAMMFAR的更多信息,请参阅[SCOTT HANSELMAN的博客文章](http://www.hanselman.com/blog/BackToBasicsDynamicImageGenerationASPNETControllersRoutingIHttpHandlersAndRunAllManagedModulesForAllRequests.aspx),以及为什么要避免它。 – 2013-08-23 13:44:22