从Body中接收一个postasync作为param



我正在尝试读取通过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,但是SendRequest方法中的stringResult始终是null

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

由于您将其发布为application/json,因此该框架试图对其进行挑选,而不是提供原始字符串。无论您的示例中的testObj的类型是什么,请将该类型用于控制器操作参数,然后返回类型而不是string

[HttpPost]
public MyTestType PostContract([FromBody] MyTestType testObj)
{
    return testObj;
}

最新更新