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 is the controller which calls a method in test calls which in turn calls the put service
public ActionResult TestEdit(Test test)
{
if (ModelState.IsValid)
{
// objTest is returned null
HttpResponseMessage objtest = TestDatabaseService.TestEdit(test.testID, test);
}
}
// Method which calls put service testDataService
public HttpResponseMessage TestEdit(int id, Test test)**
{
string uri = baseUri + "Test/" + id;
using (HttpClient httpClient = new HttpClient())
{
Task<HttpResponseMessage> response = httpClient.PutAsJsonAsync<Test>(uri, application);
return response.Result;
}
}
// The webapi service put method
public HttpResponseMessage PutTest(int id, Test test)
{
if (ModelState.IsValid && id == test).testID)
{
db.Entry(test)).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
// The status code is set to indicate the save is success
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
// If save failed
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
public Application TestCreate(Test test)
{ string uri = baseUri + "Test";
using (HttpClient httpClient = new HttpClient())
{ Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync<Test>(uri, test);
return JsonConvert.DeserializeObjectAsync<Test>(response.Result.Content.ReadAsStringAsync().Result).Result;
}
}
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
.