Get HTTP status code descriptions in ASP.Net Core

2019-04-22 19:45发布

问题:

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?

回答1:

You can use Microsoft.AspNetCore.WebUtilities.ReasonPhrases.GetReasonPhrase(int statusCode):

using Microsoft.AspNetCore.WebUtilities;

int statusCode = 404;
string reasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode);


回答2:

This is close enough for my needs:

var statusCode = httpContext.Response.StatusCode
var description = ((HttpStatusCode)statusCode).ToString(); // 404 -> "NotFound"


回答3:

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.