Get HTTP status code descriptions in ASP.Net Core

后端 未结 4 1920

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 the

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 04:57

    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.

提交回复
热议问题