【问题标题】:Returning ActionResult content in Web API在 Web API 中返回 ActionResult 内容
【发布时间】:2015-02-20 10:53:56
【问题描述】:

我的控制器下面的POST方法需要在响应中返回自定义信息:

public IHttpActionResult PostStuff(PolicyModel model)
{
      return Ok("Some useful information");
}

但是在客户端,我找不到这些数据在哪里:

client.BaseAddress = new Uri("http://localhost:51812/");
var response = client.PostAsJsonAsync("api/stuff", <my json>).Result;

'response' 只包含通常的标题信息。我可能不明白 OkResult 的用法。我应该怎么做才能返回信息?

【问题讨论】:

    标签: .net json rest asp.net-web-api


    【解决方案1】:

    在客户端中,您应该查看 response.Content 并反序列化该值(我使用的是 newtonsoft json)。示例:

    JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync())    
    

    无论如何要返回成功状态,您应该只从 API 返回它

    return Request.CreateResponse(HttpStatusCode.OK);
    

    所以客户端在响应中接收到这个信息并检查它

    if(response.IsSuccessStatusCode) { //do stuf }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2023-03-26
      相关资源
      最近更新 更多