修改 Http Status Code 文本

Modify the Http Status Code text

问题

如何修改状态码文本(description/title)?

例子

例如:我想把200 (Ok)改成200 (My Custom Text)

说明

我想创建一个带有自定义状态代码(未保留)431 的 HTTP 响应。我想修改它的文本:

我试过了:

var response = new HttpResponseMessage() 
{
    StatusCode = (HttpStatusCode) 431,
};

response.Headers.Add("Status Code", "431 My custom text"); // This throws error.

只需在初始化程序中添加 ReasonPhrase 即可:

        var response = new HttpResponseMessage()
        {
            StatusCode = (HttpStatusCode)431,
            ReasonPhrase = "your text"
        };

它定义发送消息的文本和状态码

解决此问题的一种方法是跳过对您添加的 header 的验证。这可以通过 TryAddWithoutValidation 方法来完成。

var response = new HttpResponseMessage() 
{
    StatusCode = (HttpStatusCode) 431,
};

response.Headers.TryAddWithoutValidation ("Status Code", "431 My custom text");