如何从ApiController中的StringContent对象中读取JSON?

时间:2016-11-03 17:33:57

标签: c# json asp.net-mvc asp.net-web-api async-await

我正在编写一个用于接收和解析JSON异步帖子内容的API控制器,并且无法读取该帖子中StringContent对象的内容。

以下是我的API控制器中我希望看到的值的部分。到达ApiController方法的值为null。并且jsonContent值是一个空字符串。我期待看到的是JSON对象的内容。

public class ValuesController : ApiController
{
    // POST api/values
    public void Post([FromBody]string value)
    {
        HttpContent requestContent = Request.Content;
        string jsonContent = requestContent.ReadAsStringAsync().Result;

        // Also tried this per mybirthname's suggestion.
        // But content ends up equaling 0 after this runs.
        var content = Request.Content.ReadAsStreamAsync().Result.Seek(0, System.IO.SeekOrigin.Begin);
    }
}

这是我的控制器,用于显示它是如何被调用的。

[HttpPost]
public ActionResult ClientJsonPoster(MyComplexObject myObject)
{
    this.ResponseInfo = new ResponseInfoModel();
    PostToAPI(myObject, "http://localhost:60146", "api/values").Wait();
    return View(this.ResponseInfo);
}

这是发布方法。

private async Task PostToAPI(object myObject, string endpointUri, string endpointDirectory)
{
    string myObjectAsJSON = System.Web.Helpers.Json.Encode(myObject);
    StringContent stringContent = new StringContent(myObjectAsJSON, Encoding.UTF8, "application/json");
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri(endpointUri);
        using (HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(endpointDirectory, stringContent).ConfigureAwait(false))
        {
            // Do something
        }
    }
}

我怀疑ApiController中Post方法的签名有问题。但不知道应该如何改变。谢谢你的帮助。

1 个答案:

答案 0 :(得分:4)

您正在混合异步和同步调用,这将导致死锁。

将控制器更新为

[HttpPost]
public async Task<ActionResult> ClientJsonPoster(MyComplexObject myObject) {
    this.ResponseInfo = new ResponseInfoModel();
    await PostToAPI(myObject, "http://localhost:60146", "api/values");
    return View(this.ResponseInfo);
}

此外,[FromBody]用于强制Web API从请求正文中读取简单类型。

更新Api

public class ValuesController : ApiController {
    // POST api/values
    [HttpPost]
    public async Task Post() {
        var requestContent = Request.Content;
        var jsonContent = await requestContent.ReadAsStringAsync();

    }
}