生成给定格式的响应HTTPResponseMessage

时间:2019-04-21 19:01:44

标签: c# asp.net-web-api

想要获得如下所示的Web api方法的响应。 尝试使用HttpResponseMessage,但无法以json格式正确生成。

{
    "Version": {
        "_Major": 1,
        "_Minor": 1,
        "_Build": -1,
        "_Revision": -1
    },
    "Content": {
        "Headers": [
            {
                "Key": "Content-Type",
                "Value": [
                    "text/plain; charset=utf-8"
                ]
            }
        ]
    },
    "StatusCode": 400,
    "ReasonPhrase": "<error reason>",
    "Headers": [],
    "RequestMessage": null,
    "IsSuccessStatusCode": false
}

2 个答案:

答案 0 :(得分:0)

知道了。 首先创建一个httpResponseObject,并使用相应的值填充属性。 然后将对象传递给request.CreateResponse,它将返回预期的结果。

答案 1 :(得分:-1)

您可以在下面创建对象并返回它们:

public class Version {
  public int _Major {get; set;}
  public int _Minor{get; set;}
  public int _Build{get; set;}
  public int _Revision{get; set;}
}
public class HttpReturnMessage {
  public Version Version {get; set;}
  public int StatusCode {get; set;}
  public string ReasonPhrase {get; set;}
  public string[] Headers {get; set;}
  public object RequestMessage {get; set;}
  public bool IsSuccessStatusCode {get; set;}
}

并在控制器中创建该项目并返回:

HttpReturnMessage message = new HttpReturnMessage {
  Version = new Version {
    _Major= 1,
    _Minor = 1,
    _Build = 1,
    _Revision = 1
  },
  StatusCode = 300, 
...
};

并将其返回为json