[英]HttpResponseMessage.Content.ReadAsStringAsync don't deserialize JSON when it come from CreateErrorResponse
if i return from my selfhosted webapi 如果我从我自己的主题webapi返回
Request.CreateResponse(HttpStatusCode.OK, "YAY");
everything is fine.. so i can read it like that: 一切都很好..所以我可以这样读:
var responseStr = await Client.Content.ReadAsAsync<string>();
and then make something like "MessageBox.Show(responseStr);
if i return 如果我回来
Request.CreateErrorResponse(HttpStatusCode.NotFound, "something went wrong!");
and i read it out the same way or even with(doesn't matter how): 我用同样的方式读出来,或者用(不管怎么样):
Client.Content.ReadAsStringAsync();
the string is not deserialized and i get an error when trying to parse / read as string. 该字符串未反序列化,并在尝试解析/读取为字符串时出错。
if i read it as object .. it's fine.. but i can't perform object.ToString(); 如果我把它作为对象阅读..它没关系...但我无法执行object.ToString(); i get errors.. 我收到错误..
why? 为什么? and how to fix it? 以及如何解决它?
I found that there were extra '\\' and '"' in the returned JSON. 我发现返回的JSON中有额外的'\\'和'“'。
So before I serialize back to an object, I needed to remove the extra chars. 所以在我序列化回一个对象之前,我需要删除额外的字符。
eg 例如
string jsonString = httpResponseMessage.Content.ReadAsStringAsync()
.Result
.Replace("\\", "")
.Trim(new char[1] { '"' });
List<VwAisItemMaster> vwAisItemMasterList = JsonConvert.DeserializeObject<List<VwAisItemMaster>>(jsonString);
The better solution is just to fix the issue when creating the response in the webapi method. 更好的解决方案是在webapi方法中创建响应时解决问题。 Note the type in the CreateResponse method. 请注意CreateResponse方法中的类型。
IList<VwItemMaster> vwItemMasterList = this.itemMastersGetByUpc(unitOfWork, upc);
HttpResponseMessage httpResponseMessage = this.Request.CreateResponse<IList<VwItemMaster>>(HttpStatusCode.OK, vwItemMasterList);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.