您好我正在开发一个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; }
}
application / json,text / json [API HELP PAGE]
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不要担心它
答案 0 :(得分:0)
这个问题来自异步方法,从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"));
}