在FromBody中接收PostAsync作为参数

时间:2015-05-08 09:33:06

标签: c# asp.net-mvc-4 asp.net-web-api dotnet-httpclient

我正在尝试从通过HttpClient.PostAsync()方法发送的Web API控制器读取JSON字符串。但由于某种原因,RequestBody始终为null

我的请求如下:

public string SendRequest(string requestUrl, StringContent content, HttpMethod httpMethod)
{
    var client = new HttpClient { BaseAddress = new Uri(ServerUrl) };
    var uri = new Uri(ServerUrl + requestUrl); // http://localhost/api/test

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

    HttpResponseMessage response;
    response = client.PostAsync(uri, content).Result;

    if (!response.IsSuccessStatusCode)
    {
        throw new ApplicationException(response.ToString());
    }

    string stringResult = response.Content.ReadAsStringAsync().Result;
    return stringResult;
}

我这样称呼这个方法

var content = new StringContent(JsonConvert.SerializeObject(testObj), Encoding.UTF8, "application/json");
string result = Request.SendRequest("/api/test", content, HttpMethod.Post);

现在我的Web API控制器方法现在读取这样的发送数据:

[HttpPost]
public string PostContract()
{
    string httpContent = Request.Content.ReadAsStringAsync().Result;
    return httpContent;
}

这很好用。 stringResult属性包含控制器方法返回的字符串。但是我希望我的控制器方法如下:

[HttpPost]
public string PostContract([FromBody] string httpContent)
{
    return httpContent;
}

该请求似乎有效,获得200 - OK,但stringResult方法中的SendRequest始终为null

为什么我使用RequestBody作为参数的方法不起作用?

1 个答案:

答案 0 :(得分:2)

由于您发布为application/json,因此框架正在尝试反序列化它而不是提供原始字符串。无论样本中testObj的类型是什么,请将该类型用于控制器操作参数并返回类型而不是string

[HttpPost]
public MyTestType PostContract([FromBody] MyTestType testObj)
{
    return testObj;
}
相关问题