Modify the Http Status Code text

流过昼夜 提交于 2019-12-12 18:24:30

问题


Question

How to modify the Status Code text (description/title)?

Example

For example: I want to change 200 (Ok) to 200 (My Custom Text)

Desciption

I want to create a HTTP response with custom Status Code (unreserved) 431. I want to modify it's text:

  • 200 (OK)
  • 400 (Bad Request)
  • 431 (My message here)

I've tried:

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

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

回答1:


Just add ReasonPhrase in initializer :

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

It defines text of the message that send with the status code




回答2:


One way to solve this issue is to skip the validation of the header you add. This can be done with the TryAddWithoutValidation method.

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

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


来源:https://stackoverflow.com/questions/36462721/modify-the-http-status-code-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!