WebAPI Put返回HTTPResponseMessage null

时间:2016-02-10 14:05:46

标签: jquery asp.net-mvc-3 asp.net-mvc-4 asp.net-web-api asp.net-mvc-5

我需要实现简单的编辑功能。我正在使用webapi服务来更新我的测试对象。 我从控制器发布请求中调用以下方法。

这是在测试调用中调用metod的控制器,其中调用put服务

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(测试测试) {string uri = baseUri +“Test”; 使用(HttpClient httpClient = new HttpClient())  {Task response = httpClient.PostAsJsonAsync(uri,test); 返回JsonConvert.DeserializeObjectAsync(response.Result.Content.ReadAsStringAsy nc()。Result).Result; } }

1 个答案:

答案 0 :(得分:0)

这没有任何意义:

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

已经的回复是 HttpResponseMessage

Task<HttpResponseMessage> response

没有什么可以反序列化。您所要做的就是等待它以获得结果。首先,制作方法async

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

然后等待方法中的结果:

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

这将有效地返回HttpResponseMessage对象。所以也要这个async

public async Task<ActionResult> TestEdit(Test test)

等待你的其他方法:

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

为什么你需要在多种方法背后提取这一点并不是很清楚,但如果语义对你的需求有意义,那就没问题了。没有立即伤害它。

但基本上你是在尝试告诉JSON反序列化器反序列化一些东西,而不是那些对象的JSON表示。因此结果将是null,因为反序列化将悄然失败。但关键是你不需要在这里反序列化任何东西。 PutAsJsonAsync<T>已经返回HttpResponseMessage类型的对象。

相关问题