Search code examples
c#httpwebresponse

HttpStatusCode to readable string


HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
HttpStatusCode statusCode = response.StatusCode;

In this code statusCode.ToString() returns for example "BadRequest" but I need "Bad Request"

I saw arcticles about response.ReasonPhrase, but that's not what I need and it is not supported by HttpWebResponse, only supported by HttpResponseMessage from HttpClient

Another example against Regex.Replace solution: (414) RequestUriTooLong -> Request-Uri Too Long


Solution

  • Based on reference source, you can retrieve the English status description with a simple call into a static class, given the status code:

    int code = 400;
    
    /* will assign "Bad Request" to text */
    var text = System.Web.HttpWorkerRequest.GetStatusDescription(code);
    

    Texts are defined for ranges 100 - 507, returning empty strings for special codes like 418 and 506.