WebAPI Put returns HTTPResponseMessage null

 ̄綄美尐妖づ 提交于 2019-12-02 08:15:07

This makes no sense:

JsonConvert.DeserializeObjectAsync<HttpResponseMessage>(response.Result.Content.ReadAsStringAsync().Result).Result

The response already is an HttpResponseMessage:

Task<HttpResponseMessage> response

There's nothing to deserialize. All you have to do is await it to get its result. First, make your method async:

public async Task<HttpResponseMessage> TestEdit(int id, Test test)

Then await the result in the method:

return await httpClient.PutAsJsonAsync<Test>(uri, test);

This will effectively return the HttpResponseMessage object. So make this async as well:

public async Task<ActionResult> TestEdit(Test test)

And await your other method:

HttpResponseMessage objtest = await TestDatabaseService.TestEdit(test.testID, test);

It's not really clear why you need to abstract this behind multiple methods, but if the semantics make sense for your needs then that's fine. There's no immediate harm to it.

But basically you're trying to tell a JSON de-serializer to de-serialize something that, well, isn't a JSON representation that object. So the result will be null, because the de-serialization will quietly fail. But the point is that you don't need to de-serialize anything here. PutAsJsonAsync<T> already returns an object of type HttpResponseMessage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!