Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 791
Vitaliy Avatar asked May 29 '18 15:05

Vitaliy


2 Answers

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.

like image 137
Cee McSharpface Avatar answered Sep 22 '22 02:09

Cee McSharpface


HttpStatusCode is an enum which has camel-cased member names.
You can use this one-liner to accomplish your need by putting space between camel-cased:

return Regex.Replace(statusCode.ToString(), "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
like image 36
Yan Avatar answered Sep 22 '22 02:09

Yan