0

How i do force 404 error for a particular request?

I don't wish to exclude the page from the site.

However if the user requested for the below two files, I would always return 404 Error Page NotFound.aspx

/site/employee/pensionplan.aspx

/site/employee/pensiondoc.pdf

I have been told that not to use the web.config for 404 error configuration, due to some security issues. I am not sure what exactly the problem

<!-- Turn on Custom Errors -->
<customErrors mode="On" 
  defaultRedirect="DefaultRedirectErrorPage.aspx">
  <error statusCode="404" redirect="Http404ErrorPage.aspx"/>
</customErrors>

What is the best way to redirect a user to a Not Found page when he trying to access a particular resource?

Billa
  • 5,226
  • 23
  • 61
  • 105
  • You want to leave the files there but don't want to process them? Why? And why can't you simply rename them - then a 404 would come naturally? – Olaf Oct 15 '13 at 15:26
  • @Olaf, I do use the same file later. I dont want to rename and I dont want to configure it in web.config. Please add some suggestion to handle 404 other than web.config. – Billa Oct 15 '13 at 15:28
  • 1
    Can you just redirect them from the code behind if they aren't supposed to be there? Are you using Role Management? I don't see how web.config is going to help you if you want 404 for resources that are actually there. – MikeSmithDev Oct 15 '13 at 15:34
  • I would do it from code behind as suggested by @MikeSmithDev . Can also do it by implementing a custom http module. – A Khudairy Oct 15 '13 at 15:53
  • @MikeSmithDev I dont think we will get a code behind for `/site/employee/pensiondoc.pdf` :) – Billa Oct 15 '13 at 16:18
  • 1
    @Billa sure you do, [with a HttpHandler](http://stackoverflow.com/questions/19123961/filehandler-in-asp-net/19124733#19124733). You can also lock down PDF with web.config entry for the folder it is in. – MikeSmithDev Oct 15 '13 at 16:51

1 Answers1

0

To make it easy, put this in your Http404ErrorPage.aspx codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    Response.StatusCode = 404;
}

And have this in your web.config:

<location path="site/employee/pensionplan.aspx">
<system.webServer>
  <httpRedirect enabled="true" destination="http://www.website.com/Http404ErrorPage.aspx" httpResponseStatus="Permanent" />
</system.webServer>
</location>
<location path="site/employee/pensiondoc.pdf">
<system.webServer>
  <httpRedirect enabled="true" destination="http://www.website.com/Http404ErrorPage.aspx" httpResponseStatus="Permanent" />
</system.webServer>
</location>

A more robust solution would be to use an HttpHandler as MikeSmithDev recommends, that way you can control whether the user is 404'd or not.

Zerkey
  • 795
  • 1
  • 6
  • 16