我有一个web-Api方法验证用户的条目,并在任何验证错误时返回BadRequest(ModelState)
。到目前为止一切都很好
public async Task<IHttpActionResult> Register(RegisterModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
...
}
现在,在我的Xamarin应用程序中,我想将返回的json
返回到Object
。我尝试使用JsonConvert.DeserializeObject
,它返回null!?
我在dotnetfiddle上构建了一个示例应用,它运行正常。
public class Program
{
public static void Main()
{
var content = "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"UserName\":[\"user name is required\"],\"Password\":[\"password is required\"]}}";
var details = JsonConvert.DeserializeObject<ModelStateErrorModel>(content);
foreach(var detail in details.ModelState)
Console.WriteLine("Key [{0}] and Message [{1}]",detail.Key,detail.Value[0]);
}
}
public class ModelStateErrorModel
{
public string Message{get;set;}
public Dictionary<string,string[]> ModelState{get;set;}
}
我的Xamarin设置
我在Xamarin中使用的代码如下
if (response.StatusCode == HttpStatusCode.BadRequest)
{
var details = JsonConvert.DeserializeObject<ModelStateErrorModel>(content);
return details; // here the value of details is always null
}
我无法弄清楚为什么deserialize返回null,任何帮助都会受到高度赞赏
答案 0 :(得分:1)
尝试这样的事情......
var json = JsonConvert.SerializeObject(ObjectOfTheClassToBeSerialized);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(LinkToTheWebService, content);
if (response.IsSuccessStatusCode){
var item = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TypeOfTheClassToBeDeSerialized>(item);
}
答案 1 :(得分:1)
您正在使用async
方法。您的代码可能返回null,因为您没有等到方法Deserialize
完成。
您能否确认这是否属于您的情况?
Task.Run
Wait();
示例强>
ModelStateErrorModel details = null;
Task.Run(()=>{
if (response.StatusCode == HttpStatusCode.BadRequest)
{
details = JsonConvert.DeserializeObject<ModelStateErrorModel>(content);
}
}).Wait();
return details;
希望这会对你有所帮助