Access session in IHttpModule and being able to do a response.redirect
Following the solution found at Can I access session state from an HTTPModule?, I am able to access the session state from an IHttpModule. I'm using it to control access to some files, so in the event someone doesn't have access, I would like to redirect them to a login page. When I try to do a HttpContext.Current.Response.Redirect(page); it locks the web server up. So my post acquire request state function looks like this...
void Application_PostAcquireRequestState(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;
if (resourceHttpHandler != null)
{
// set the original handler back
HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
}
HttpContext context = HttpContext.Current;
string filePath = context.Request.FilePath;
context.Trace.Write("HttpDownloadModule", "File path: " + filePath);
Boolean ha开发者_Python百科sAccess = true;
if (filePath.Contains("content/downloads"))
{
//check to make sure a session has been established already....
if (context.Session == null)
hasAccess = false;
SecurityBLL security = new SecurityBLL();
string fileName = filePath.Split('/').Last();
//check to see if a user is logged in
if (!CitrixAccess.loggedin)
hasAccess = false;
//check access for download
if (!security.checkSecurityByDownload(fileName))
hasAccess = false;
if (!hasAccess)
{
HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
HttpContext.Current.Response.Redirect("../../login.aspx");
}
}
}
Any thoughts? Thanks for the help!
Ok, so I found a workaround... I moved my hasAccess variable to be global and added an EndRequest handler. So I'm checking for hasAccess in EndRequest and doing the redirect from there.
My answer includes Arthurdent510's answer but I don't have enough reputation to simply comment on his answer haha. His answer helped me A LOT to figure out where I had to go, but it wasn't quite complete for me.
Putting the Response.Redirect call in the EndRequest handler caused an infinite loop. I think this is because the Response.Redirect causes EndRequest to be called. So EndRequest was being called over and over forever.
To get around this, I added a private boolean to indicate if I already called for the redirect. If I already called for the redirect, then I won't call Response.Redirect again. This is what my EndRequest method looked like:
Private Sub Application_EndRequest(ByVal source As Object, ByVal e As EventArgs)
If Not _blnHasAccess AndAlso Not _blnRedirected Then
_blnRedirected = True
HttpContext.Current.Response.Redirect("~/Error.aspx")
End If
End Sub
精彩评论