在 FromBody 中接收一个 PostAsync 作为参数

Receive a PostAsync in FromBody as param

我正在尝试从 Web API 控制器读取 JSON 字符串,该字符串通过 HttpClient.PostAsync() 方法发送。但由于某种原因 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 的类型是什么,请使用该类型作为控制器操作参数和 return 类型而不是 string

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