I'm attempting to turn a 401 response into a redirect without changing the response code. The code below was working before, but I did some fiddling to figure out some other issues, and now this won't work, and I can't figure out why.
What really boggles me is that when I step through the code, it hits the Response.Output.Write lines and does not throw any errors (I've also tried Response.Write), but when the browser receives the response, the normal IIS error page shows up.
Any idea why IIS would not be using the response content that I'm giving it?
This is IIS7 on Server 2008 R2. Website is running in .NET 4.0 (tried 4.5 and same thing happens).
This is the code in my Global.asax file:
protected void Application_EndRequest(Object sender, EventArgs e) {
if (Request.Url.ToString().Contains("WinLogin.aspx") && HttpContext.Current.Response.StatusCode == 401) {
HttpContext.Current.Response.ClearContent();
//If Windows authentication failed, redirect to the forms login page
if (String.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) {
HttpContext.Current.Response.Output.Write(@"<html><head><script language='javascript'>self.location='/Login.aspx?ReturnUrl=/';</" + "script></head><body>401 Unauthorized</body></html>");
} else {
HttpContext.Current.Response.Output.Write(@"<html><head><script language='javascript'>self.location='/Login.aspx?ReturnUrl=" + Request.QueryString["ReturnUrl"] + "';</" + "script></head><body>401 Unauthorized</body></html>");
}
}
}
Update: I figured out that this problem is only happening from remote machines (I was using a VM that's not joined to a domain to test). It works fine from my local machine. I'm going to do some searching online from that angle.
Ok, I've figured it out. I have to enable detailed IIS errors in the web.config. The default is DetailedLocalOnly.
<httpErrors errorMode="Detailed" />
I had tried the customErrors tag, but that's only for ASP.NET errors, so it had no effect.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments