在 Web 中返回 ActionResult 内容 API

Returning ActionResult content in Web API

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

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' 只包含通常的 header 信息。我可能不明白 OkResult 的用法。 return 返回信息怎么办?

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

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

无论如何 returning 成功状态你应该 return 这个来自 API

return Request.CreateResponse(HttpStatusCode.OK);

因此客户端在响应中收到此信息并进行检查

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