为图像请求执行Application_AuthenticateRequest

时间:2010-08-23 18:15:34

标签: asp.net authentication

我在Global.asax中使用Application_OnAuthenticateRequest为HttpContext.Current.User和System.Threading.Thread.CurrentPrincipal分配自定义主体。
在测试中,我注意到此代码对单个页面请求执行多次。通过查看HttpContext.Current.Request.Url,我确定每次调用JavaScript文件,Image和CSS文件时都会执行此代码。所有这些资源都存储在名为“Content”的单个子文件夹中。所以,我可以通过检查“Content”是否是HttpContext.Current.Request.Url的一部分来阻止我的自定义主体的多次执行:

protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
{
    if (HttpContext.Current.Request.Url.AbsoluteUri.Contains("/Content"))
        return;

    if (Context.User != null)
    {
        if (Context.User.Identity.IsAuthenticated)
        {
            var userRepository = ObjectFactory.GetInstance<IUserRepository>();

            var prospectorUser = userRepository.GetByUserName(Context.User.Identity.Name);

            if (prospectorUser == null)
            {
                throw new ApplicationException("Context.User.Identity.Name is not a recognised user.");
            }

            var principal = new ExtendedWindowsPrincipal(HttpContext.Current.User.Identity, prospectorUser);

            // Attach the new principal object to the current HttpContext object
            HttpContext.Current.User = principal;
            // Make sure the Principal's are in sync
            System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User;
            return;
        }
    }
}

我的修复似乎很糟糕。是否有更好的方法来捕获“内容”项目的请求,并阻止我的主体的自定义代码为每个请求触发?

2 个答案:

答案 0 :(得分:0)

简单的答案是修改您的web.config以使“Content”文件夹可以匿名访问:

<location path="Content">
    <system.web>
        <authorization>
            <allow users ="*" />
        </authorization>
    </system.web>
</location>

答案 1 :(得分:0)

AuthenticateRequest事件在HTTP管道中非常高。如果你想在某些情况下为你的应用程序绕过它,你可能需要写一个注册的HttpModule来处理给定的路径。

请看下面文章中的图9,10和11。您应该能够按照它来构建自定义模块来处理对内容路径的请求,并绕过所有常规事件处理。

Securely Implement Request Processing, Filtering, and Content Redirection with HTTP Pipelines in ASP.NET