放的WebAPI回报HTT presponseMessage空 [英] WebAPI Put returns HTTPResponseMessage null

查看:96
本文介绍了放的WebAPI回报HTT presponseMessage空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现functionality.I正在使用的WebAPI服务来更新我的测试对象,简单的编辑的要求。
我打电话从控制器POST请求下面的方法。

这是它调用了测试呼叫梅托德至极inturn控制器调用看跌服务

 公众的ActionResult TestEdit(测试试验)
{
  如果(ModelState.IsValid)
  {
    // objTest返回null
    HTT presponseMessage objtest = TestDatabaseService.TestEdit(test.testID,测试);
  }
}//方法,它调用放服务testDataService
公众的Htt presponseMessage TestEdit(INT ID,测试试验)**
{
   字符串URI =基本URI +测试/+ ID;
   使用(HttpClient的HttpClient的=新的HttpClient())
   {
      任务< Htt的presponseMessage>响应= httpClient.PutAsJsonAsync&所述;试验>(URI,应用程序);
            返回response.Result;
   }
}//该服务的WebAPI put方法
公众的Htt presponseMessage PutTest(INT ID,测试试验)
{
  如果(ModelState.IsValid&安培;和ID ==测试).testID)
  {
    db.Entry(试验))状态= EntityState.Modified。    尝试
    {
      db.SaveChanges();
    }
    赶上(DbUpdateConcurrencyException)
    {
      返回Request.CreateResponse(的HTTPStatus code.NotFound);
    }    //状态code设置为指示保存是成功的
    返回Request.CreateResponse(的HTTPStatus code.OK);
  }
  其他
  {
    //如果保存失败
    返回Request.CreateResponse(的HTTPStatus code.BadRequest);
  }
}


 公共应用TestCreate(测试试验)
{字符串URI =基本URI +测试;
使用(HttpClient的HttpClient的=新的HttpClient())
 {任务响应= httpClient.PostAsJsonAsync(URI,测试);
返回JsonConvert.DeserializeObjectAsync(response.Result.Content.ReadAsStringAsy NC()的结果。)。结果;
}
}


解决方案

这是没有意义的:

<$p$p><$c$c>JsonConvert.DeserializeObjectAsync<Htt$p$psponseMessage>(response.Result.Content.ReadAsStringAsync().Result).Result

响应已经的的一个的Htt presponseMessage

 任务&LT; Htt的presponseMessage&GT;响应

有什么反序列化。所有你需要做的就是的await 的它得到它的结果。首先,让你的方法异步

 公共异步任务&LT; Htt的presponseMessage&GT; TestEdit(INT ID,测试试验)

然后等待结果的方法:

 返回等待httpClient.PutAsJsonAsync&LT;试验&gt;(URI,测试);

这将有效地返回的Htt presponseMessage 对象。所以,让这个异步以及

 公共异步任务&LT;&的ActionResult GT; TestEdit(测试试验)

和等待着你的另一种方法:

 的Htt presponseMessage objtest =等待TestDatabaseService.TestEdit(test.testID,测试);

这不是真的不清楚为什么你需要这个抽象背后多种方法,但如果语义为您的需要有意义那么这很好。有没有直接危害到它。

但基本上你想讲一个JSON解串器反序列化的东西,那么,是不是一个JSON重新presentation该对象。因此,其结果将是,因为反序列化会悄悄地失败。但问题是,你并不需要在这里反序列东西。 PutAsJsonAsync&LT; T&GT; 已返回类型的对象的Htt presponseMessage

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 metod in test calls wich inturn 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 response = httpClient.PostAsJsonAsync(uri, test); return JsonConvert.DeserializeObjectAsync(response.Result.Content.ReadAsStringAsy‌​nc().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.

这篇关于放的WebAPI回报HTT presponseMessage空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆