Reputation: 73908
I use Asp.net 4 C# and IIS 7 locally and IIS 7.5 on Production Server.
I need display Custom Error Pages. At the moment I use some logic in my Global.asax to bypass IIS default pages.
Locally using IIS 7 I was able to successfully display CustomPages but on production (IIS 7.5) Server defaults IIS pages persists.
I use Response.TrySkipIisCustomErrors = true;
but on Production Server does not work.
Could you point me out a solution to this problem?
My code in Global.Asax
Application_Error
Response.TrySkipIisCustomErrors = true;
if (ex is HttpException)
{
if (((HttpException)(ex)).GetHttpCode() == 404)
{
Server.Transfer("~/ErrorPages/404.aspx");
}
}
// Code that runs when an unhandled error occurs.
Server.Transfer("~/ErrorPages/Error.aspx");
Upvotes: 1
Views: 2141
Reputation: 5241
The way I have done it is in a module rather than the Global.asax and hooked it into the standard custom error stuff. Give this a try:
public class PageNotFoundModule : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.Error += new EventHandler(context_Error);
}
private void context_Error(object sender, EventArgs e)
{
var context = HttpContext.Current;
// Only handle 404 errors
var error = context.Server.GetLastError() as HttpException;
if (error.GetHttpCode() == 404)
{
//We can still use the web.config custom errors information to decide whether to redirect
var config = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors");
if (config.Mode == CustomErrorsMode.On || (config.Mode == CustomErrorsMode.RemoteOnly && context.Request.Url.Host != "localhost"))
{
//Set the response status code
context.Response.StatusCode = 404;
//Tell IIS 7 not to hijack the response (see http://www.west-wind.com/weblog/posts/745738.aspx)
context.Response.TrySkipIisCustomErrors = true;
//Clear the error otherwise it'll get handled as usual
context.Server.ClearError();
//Transfer (not redirect) to the 404 error page from the web.config
if (config.Errors["404"] != null)
{
HttpContext.Current.Server.Transfer(config.Errors["404"].Redirect);
}
else
{
HttpContext.Current.Server.Transfer(config.DefaultRedirect);
}
}
}
}
}
Upvotes: 2