WebAPI Put返回HTTPResponseMessage null
我需要实现简单的编辑function。我正在使用webapi服务来更新我的测试对象。 我从控制器发布请求中调用以下方法。
这是在调用put服务时调用metod的控制器
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 response = httpClient.PutAsJsonAsync(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(测试测试){string uri = baseUri +“Test”; using(HttpClient httpClient = new HttpClient()){Task response = httpClient.PostAsJsonAsync(uri,test); 返回JsonConvert.DeserializeObjectAsync(response.Result.Content.ReadAsStringAsy nc()。Result).Result; }}
这毫无意义:
JsonConvert.DeserializeObjectAsync(response.Result.Content.ReadAsStringAsync().Result).Result
响应已经是 HttpResponseMessage
:
Task response
没有什么可以反序列化。 您所要做的就是等待它获得结果。 首先,使您的方法async
:
public async Task TestEdit(int id, Test test)
然后等待方法中的结果:
return await httpClient.PutAsJsonAsync(uri, test);
这将有效地返回HttpResponseMessage
对象。 所以async
使这个async
:
public async Task TestEdit(Test test)
等待你的其他方法:
HttpResponseMessage objtest = await TestDatabaseService.TestEdit(test.testID, test);
不清楚为什么你需要在多个方法背后提取它,但如果语义对你的需求有意义那么那就没关系。 它不会立即受到伤害。
但基本上你是在尝试告诉JSON反序列化器反序列化一些东西,这些东西不是对象的JSON表示。 因此结果将为null
,因为反序列化将悄然失败。 但关键是你不需要在这里反序列化任何东西。 PutAsJsonAsync
已经返回HttpResponseMessage
类型的对象。