How do I generate a 404 error from an HttpModule? - asp.net

I have an ASP.NET HttpModule that handles HttpApplication.BeginRequest to redirect some requests to other files. Typically I'll do something like parse the request, write a file to HttpContext.Current.Response.OutputStream then call HttpApplication.CompleteRequest(). For some requests I can't find the relevant file - how do I return a 404 error?

Have you tried throw new HttpException(404, "Not Found");?

Related

How to properly set status code for HTTPContext

I am working with webforms and as such I have a website running on IIS 8 on a server 2012, using vb.net. We have some URL redirection happening on Global.asax, on the Application_BeginRequest event which opens an XML file and compares the incoming request to what it would be translated to in the XML. If the request cannot be satisfied by searching the XML, then we need to first raise a 410 status code, then redirect to a generic page. So, the way I've been trying to do this is
HttpContext.Current.Items.Add("Raise410", "true")
HttpContext.Current.Items.Add("Redirect", "/" + dv(0)("folder"))
Throw New HttpException(410, "Gone")
Then on the exception catch I do this:
Catch ex As Exception
If HttpContext.Current.Items("Raise410") IsNot Nothing Then
HttpContext.Current.Response.StatusCode = 410
HttpContext.Current.Response.Redirect(HttpContext.Current.Items("Redirect"))
End If
End Try
However all I am getting is a 302 redirect and the 410 is never raised. I am not sure why and I've tried to figure this out for several hours to no avail.
There's some design flaw in your approach. Both 410 Gone and 301 Redirect are HTTP status codes.
You can't return a response and then redirect from server code.
One possible approach is returning HTTP/410 from the server side and do the redirect in the client-side using META refresh or using a setTimeout and setting window.location to the URL where you want to redirect:
setTimeout(function() {
window.location = "http://";
}, 6000); // 6 seconds and do the redirect

Application_Error is not fired on 404 error

I use an Application_Error handler to log all unhandled exceptions; generally it works well, but 404 errors always are skipped. Any ideas what might be the reason?
Actually, that is because that's an http protocol error returned by your web server. It's not a .net framework exception and thus it can't be handled by asp.net. However, you can configure IIS to serve a custom page when it returns a 404 error and this can be done through your web.config file. Needless to say that this custom page could be an aspx page where you can add some custom processing such as logging the error ;)
404's are not always caused by exceptions. You can just set the Response.Status* fields to generate a 404 response.
Use Application_EndRequest to examine the response and act on it.

Throw to 404 error page if a bad route is found?

I use ASP.Net URL Routing for SEO and when I run into a routename that is bad in (i.e. /Games/{RouteName}) I want to pass it to my 404 page for handeling. I check the DB to make sure {RouteName} is a valid name for a game. If the RouteName is valid I want to continue processing as normal but if the DB comes back and does not find a corisponding RouteName I would like to some how have the server act as if a truly bad URL was entered. How can I best accomplish this?
I would suggest throwing a 404 error inside your logic that determines it is not valid, e.g.
if (!<validRouteName>) {
return new HttpStatusCodeResult(404, "Game not found.");
}
Doing a bit of messing around in IIS I have figure this out. As endyourif suggested I need to throw a 404 resposne in my code behind, which was done by Response.StatusCode = 404; I also had to configure IIS's Error Pages for the 404 to point to my 404.aspx page.

Custom 404 redirect for a site with URL rewriting

In my site, I have used IIS7's URL rewrite module to redirect URLs like http://mysite.com/File.aspx?Name=SomeName into http://mysite.com/SomeName.
It appears that IIS7 has created a corresponding rule check, so that any URL of the sort http://mysite.com/SomeURL is redirected to File.aspx. This is fine in most cases, when the URL is correctly rewritten.
The problem is that in some cases, the file no longer exists - http://mysite.com/SomeName2 will still get redirected to http://mysite.com/File.aspx?Name=SomeName2.
I want to show a custom 404 error page for this URL - how do I trigger the 404 error in global.asax (I have set application error logging and handling in global.asax)? The below code doesn't work.
Response.Status = "404 Not Found"
Response.AddHeader("Location", "http://mysite.com/Invalid-File.aspx?" & Request.QueryString.ToString)
It just shows the ugly default IIS 404 error page. Adding a customerror in web.config doesn't help.
Thanks for your help!
When setting a status code you need to prevent IIS taking over based on your new error code, make sure to set Response.TrySkipIisCustomErrors like this:
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.NotFound;
Response.AddHeader("Location", "http://mysite.com/Invalid-File.aspx?" & Request.QueryString.ToString)
Did you try setting the 404 error page in the IIS admin equal to what you're specifying in the web.config? I wonder if .net isn't jumping into the pipeline at the right time.
you could potentially use the Application_Error method and then do a response.redirect to the required page with the correct status code

HTTP header 411 error in asp.net

I have .aspx file with some simple logic. This file can be accessed only using HTTP Post method. My problem is that in some registration form (regnow) they ask me to supply the url (my .aspx url) and the access method (Post or Get). I select the Post and then they try to access the url and get HTTP 411 error (header missing content-length).
Is there a way to prevent the web application from sending back this error? maybe some kind of configuration in the web.config file?
Thank you very much,
Adi Barda

Resources