【问题标题】:Receive a PostAsync in FromBody as param在 FromBody 中接收 PostAsync 作为参数
【发布时间】:2015-05-08 09:33:06
【问题描述】:

我正在尝试从通过 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 作为参数的方法不起作用?

【问题讨论】:

  • 您忘记向我们展示实际内容是什么。给出一个你想使用[FromBody] 获得的示例内容
  • @MatíasFidemraizer 我添加了我如何调用SendRequest 方法的代码。我基本上将一个对象转换为 JSON 字符串并将其作为原始内容发送。
  • 这不是在正文中寻找名为 httpContent 的表单变量吗?
  • 我认为您可以使用自定义活页夹来完成,该活页夹与您的工作示例具有相同的代码
  • @ToddMenier 这确实是问题所在。我将 JSON 发送到我的控制器,但控制器想要将其转换回对象。似乎您不能简单地获取 JSON 字符串本身。在我的情况下这没关系。所以将参数更改为PostContract([FromBody] Contract contract) 就可以了。您能否将其发布为答案,以便我接受。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多