Get description for HTTP status code
Asked Answered
B

3

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?

Blent answered 22/8, 2010 at 18:55 Comment(0)
R
27

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

Retharethink answered 22/8, 2010 at 20:38 Comment(1)
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.Calistacalisthenics
L
5

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

Livelong answered 22/8, 2010 at 20:51 Comment(0)
J
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)
{    
}
Johen answered 9/3, 2011 at 15:38 Comment(4)
This can't be a client-side code because it's C#, then server-side only.Leper
Client side only, I haven't tested on the server side, but this works on the client side.Johen
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 ?Lifeanddeath
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 <% %>).Poacher

© 2022 - 2024 — McMap. All rights reserved.