Get HTTP status code descriptions in ASP.Net Core

2019-04-22 19:57发布

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?

3条回答
够拽才男人
2楼-- · 2019-04-22 19:59

This is close enough for my needs:

var statusCode = httpContext.Response.StatusCode
var description = ((HttpStatusCode)statusCode).ToString(); // 404 -> "NotFound"
查看更多
等我变得足够好
3楼-- · 2019-04-22 20:02

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

using Microsoft.AspNetCore.WebUtilities;

int statusCode = 404;
string reasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode);
查看更多
何必那么认真
4楼-- · 2019-04-22 20:14

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.

查看更多
登录 后发表回答