14

In ASP.NET you can set the Response.StatusCode to for example 404. Should the status line / description always be set? (to in this case "404 Page Not Found")

How do you get the description if you only have the code (404)? Is this somewhere in the framework or do you manually have to hardcode the descriptions?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
jaap
  • 163
  • 1
  • 1
  • 5

3 Answers3

27

You can use the static method HttpWorkerRequest.GetStatusDescription for this.

Ronald Wildenberg
  • 31,634
  • 14
  • 90
  • 133
  • 4
    This answer isn't applicable to client-profile .NET where `System.Web.dll` is unavailable, or in .NET Core where `System.Web is removed, unfortunately. – Dai Mar 14 '21 at 08:02
5

If you need it at the same time you're pulling Response.StatusCode, you can get the description from Response.StatusDescription.

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
2

The status description can be retrieved with some crazy type casting. Here is the code snipped which retrieves the custom exception message (this is client side code only)

try
{
    string exText = ((HttpWebResponse)w.Response).StatusDescription);
}
catch (WebException w)
{    
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
zyzzyxx
  • 323
  • 2
  • 9
  • 3
    This can't be a client-side code because it's C#, then server-side **only**. – abatishchev Mar 09 '11 at 15:41
  • Client side only, I haven't tested on the server side, but this works on the client side. – zyzzyxx Apr 13 '13 at 00:23
  • 1
    You're both right. It's "Client side" if the client is a .NET software. But how to retrieve it if it's another language ? Where this StatusDescription is in the raw HTTP response ? – DestyNova Jul 16 '15 at 09:43
  • The above code is not remotely close to being client-side. It is compiled before execution and the compiled code is typically placed in a library before use. Client-side code do not need compilation. It may though appear as client-side, when the code is placed in the aspx file (using <% %>). – Thomas Williams Nov 01 '19 at 21:45