I have a requirement to implement simple edit functionality.I am using webapi service to update my test object. I am calling the below method from the controller post request.
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
.