37

I'm writing an HTTP handler in ASP.NET 4.0 and IIS7 and I need to generate a file-not-found condition.

I copied the following code from Mathew McDonald's new book, Pro ASP.Net 4 in C# 2010. (The response variable is an instance of the current HttpResponse.)

response.Status = "File not found";
response.StatusCode = 404;

However, I found that the first line generates the run-time error HTTP status string is not valid.

If, instead of the lines above, I use the following:

response.Status = "404 Not found";

Then everything seems to work fine. In fact, I even see that response.StatusCode is set to 404 automatically.

My problem is that I don't want this to fail on the production server. So I'd feel much better if I could understand the "correct" way to accomplish this. Why did the first approach work for Mathew McDonald but not for me? And is the second approach always going to be reliable?

Can anyone offer any tips?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

1 Answers1

67

That's because the Status property is the complete status line sent to the client, not only the message.

You can either write:

response.Status = "404 File not found";

Or, preferably:

response.StatusCode = 404;
response.StatusDescription = "File not found";

Note that, according to its documentation, HttpResponse.Status is deprecated in favor of HttpResponse.StatusDescription.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • Well, that still leaves me in the dark as to how the other code I got from a book ever worked. – Jonathan Wood Jan 09 '11 at 15:46
  • 10
    Also, if anyone's interested, setting StatusCode to 404 automatically sets StatusDescription to "Not found". However, it's hard to know what the exact rules are (and will be in the future) because this is so very poorly documented. Setting both StatusCode and StatusDescription may be the best approach. – Jonathan Wood Jan 09 '11 at 16:45
  • 2
    Without wishing to be too pedantic, I would set the description to simply "Not Found" rather than "File Not Found" because the intent of the error is that there is no resource with that URL rather than the fact that a file is not on the disk. – Andy Dec 21 '13 at 16:41
  • 1
    that was something, I really hit my head in the wall because of this one, thanks a lot – Muhammad Nour Oct 13 '14 at 23:50