In previous versions of ASP.Net, we could retrieve the description of a HTTP status code in a few ways as shown here:
Get description for HTTP status code
Is there something similar to HttpWorkerRequest.GetStatusDescription
in ASP.Net Core?
In previous versions of ASP.Net, we could retrieve the description of a HTTP status code in a few ways as shown here:
Get description for HTTP status code
Is there something similar to HttpWorkerRequest.GetStatusDescription
in ASP.Net Core?
You can use Microsoft.AspNetCore.WebUtilities.ReasonPhrases.GetReasonPhrase(int statusCode)
:
using Microsoft.AspNetCore.WebUtilities;
int statusCode = 404;
string reasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode);
This is close enough for my needs:
var statusCode = httpContext.Response.StatusCode
var description = ((HttpStatusCode)statusCode).ToString(); // 404 -> "NotFound"
Improving on the previous answer, you could split HttpStatusCode
enum name with spaces, e.g.:
public string GetStatusReason(int statusCode)
{
var key = ((HttpStatusCode) statusCode).ToString();
return string.Concat(
key.Select((c, i) =>
char.IsUpper(c) && i > 0
? " " + c.ToString()
: c.ToString()
)
);
}
Or if you prefer regular expressions:
public string GetStatusReason(int statusCode)
{
var key = ((HttpStatusCode) statusCode).ToString();
return Regex.Replace(key, "(\\B[A-Z])", " $1");
}
Also you can simplify it to just this:
public string GetStatusReason(HttpStatusCode statusCode)
{
var key = statusCode.ToString();
return Regex.Replace(key, "(\\B[A-Z])", " $1");
}
Looking at the enum key names they seem to be pretty reasonably named so most, if not all, status codes should yield acceptable reason messages.