【问题标题】:Asp.net web api json interractionAsp.net web api json交互
【发布时间】:2015-07-09 13:02:42
【问题描述】:

您好,我正在开发一个 azure web api,我的 put 方法如下

  public string[] Put(SampleRequest request)
        {

            //Getting Request initials
            string[] filmNames = request.Inputs.FilmIds;
            int userAge = request.Inputs.UserAge;
            char userGender = request.Inputs.UserGender;
            int userId = request.Inputs.UserId;
            .
            .
            . Doesnt matter rest of them...

当我尝试与 json 通信时,我的 put 方法中的请求(它是一个 SampleRequest 对象)正在变为 null,因此我无法解析它以获取其中的数据,这会是什么问题?我的数据模型、帮助页面 json 格式和我的 json 请求(在另一个应用程序中)如下

public class SampleRequest
    {
        public InputsRequest Inputs { get; set; }
    }

    public class InputsRequest
    {
        public int UserId { get; set; }
        public int UserAge { get; set; }
        public char UserGender { get; set; }
        public string[] FilmIds { get; set; }
    }

应用程序/json,文本/json [API 帮助页面]

Sample:
{
  "Inputs": {
    "UserId": 1,
    "UserAge": 2,
    "UserGender": "A",
    "FilmIds": [
      "sample string 1",
      "sample string 2"
    ]
  }
}

我来自其他应用的请求:

      var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:5291/api/values");
      httpWebRequest.ContentType = "text/json";
      httpWebRequest.Method = "PUT";

      var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
      string json = "{"+"\"Inputs\""+":"+"{"+ "\"UserId\"" + ":" + "12345" + "," 
                                    + "\"UserAge\"" + ":" + "23" + "," 
                                    + "\"UserGender\"" + ":" + "\"M\"" + "," 
                                    + "\"FilmIds\"" + ":" + 
"[\"Kung Fu Panda\",\"I Am Legend\",\"I Am Number Four\"]"+
                                    "}"+"}";

      streamWriter.Write(json);

      var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
      using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
      {
      var responseText = streamReader.ReadToEnd();
      }

快速说明:是的,我知道名称是 FilmIds,但我得到的是电影名称:D 不用担心

【问题讨论】:

    标签: asp.net json azure asp.net-web-api


    【解决方案1】:

    这个问题来自异步方法,从put函数获取null背后的原因是测试应用程序没有发送它所有的消息,所以put方法什么都没有,解决方案是使用下面的Putasync方法

     using (var htc = new HttpClient())
                {
                    var res = await htc.PutAsync("http://localhost:5291/api/values", new StringContent(serializedObject, Encoding.UTF8, "application/json"));
                }
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多