Search code examples
c#asp.net.netasp.net-mvchttp-status-codes

How to return a 404 error for non-existent page?


I am working on a .NET/C# documentation web app. When a link on the website is clicked it fetches the document by name and displays the page.

The process is these document names have spaces in them, so when a link on the website is clicked the request replaces spaces with %20 while sending. That request url is being stripped off of the %20 to get the actual document name with spaces on the backend.

The problem is if I type in the document name on the url without spaces it's giving me internal error instead of 404 error. Does anyone know how to fix this?

Eg:

  • Document Name: Installation Prereq.md
  • Actual URL: /home/documentation/Installation%20Prereq.md --> this successfully returns the doc

But,

  • Error URL: /home/documentation/InstallationPrereq.d --> this returns 500 error, I would like to set this upto 404 error, as there is no document with such a name.

Solution

  • .NET throws an exception when you try to access/return a file that does not exist. This exception is catched by IIS (if your application does not handle it) which returns a HTTP response with 500 status code.

    The solution would be to check if the file exists, ie File.Exists("folder/filename")

    And if it returns false, let it know to your controller's action, which it turns can return a response with 404 status code:

    public ActionResult ControllerAction(string filename)
    {
        var theFile = TryFindFile(filename, out fileFound);
    
        if (fileFound == false)
            return new HttpNotFoundResult(); // this returns a HTTP response with 404 status code
    
        return theFile;
    }