ASP.NET 404 httpmodule

1.5k views Asked by At

Im using a CMS product called EPiServer. We need to create our own method of displaying 404's which just can't be achieved using .NET's standard customErrors. We've writen a module which we use to check for the HttpStatusCode. We do this in the EndRequest method.

If the status is 404, we query EPiServer for the appropriate 404 page, and then Transfer the request over to that page. However this doesnt return a 404, and even if I do the following the correct status isnt returned:

HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.StatusDescription = "Page not Found";
HttpContext.Current.Server.TransferRequest(newPage);

Likewise, if I do a response.redirect instead of a TransferRequest then its not a proper 404 because the url has then changed...

Whats the right way of doing this?

Thanks in advance Al

5

There are 5 answers

0
terjetyl On

Not a direct answer to your question but could also take a look at this open source 404 handler: https://www.coderesort.com/p/epicode/wiki/404Handler

It is also available on episervers nuget feed

0
Johan Kronberg On

Which IIS version are you using? For IIS7 or 7.5 you might need something like this:

<httpErrors errorMode="Custom">
        <remove statusCode="404" />
        <error statusCode="404" path="/somenotfoundpage.aspx" responseMode="ExecuteURL" />
        <remove statusCode="500" />
        <error statusCode="500" path="/someerrorpage.aspx" responseMode="ExecuteURL" />
</httpErrors>
0
Greg B On

You should set the status code in the codebehind of the template you're using for your 404 page.

If this is a plain content page, either create a new template or add a Status Code property to the page and logic in the code behind to send the appropriate header if this is not null or empty.

0
darasd On

Try setting the status code on the page that you transfer to - in your error page template. I'm not sure that having a separate module is necessary - you can simply handle the HttpApplication's Error event in Global.asax.cs.

0
higgsy On

Thanks for your responses.

I actually got this working by doing the following:

In the EndRequest event handler I transferred the request off to the correct EPiServer page, and included a querystring param in the call i.e.

app.Context.Server.TransferRequest(pageUrl + "&internal=true");

Then in the PostRequestHandlerExecute event I check for the querystring param, if it exists it can only be because it's a 404 so I return the correct status:

HttpContext.Current.Response.StatusCode = 404; HttpContext.Current.Response.StatusDescription = "Page not Found";

Works like a charm.

Thanks higgsy