【问题标题】:HttpClient send null POST dataHttpClient 发送空 POST 数据
【发布时间】:2017-12-25 14:34:15
【问题描述】:

嗯...我在 StackOverflow 中阅读了很多问题,但仍然没有得到答案,我有这个 Web API 控制器:

public class ERSController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        resposne.Content = new StringContent("test OK");
        return resposne;
    }

    [HttpPost]
    public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        //Some actions with database
        resposne.Content = new StringContent("Added");
        return resposne;
    }

}

我给它写了一个小测试器:

static void Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:54916/");
    client.DefaultRequestHeaders.Accept.Clear();


    var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");

    var response = client.PostAsync("api/ERS?ID=123", content);

    response.ContinueWith(p =>
    {
        string result = p.Result.Content.ReadAsStringAsync().Result;
        Console.WriteLine(result);
    });
    Console.ReadKey();
}

我总是在 API 中的参数 Data 上得到 NULL

我尝试将这些行添加到测试器:

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

还是NULL,我也把内容替换成:

var values = new Dictionary<string, string>();
values.Add("Data", "Data");
var content = new FormUrlEncodedContent(values);

还是NULL

我尝试将请求切换到:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

var values = new NameValueCollection();
values["Data"] = "hello";
var task = client.UploadValuesTaskAsync("http://localhost:54916/api/ERS?ID=123", values);
task.ContinueWith((p) =>
{
    string response = Encoding.UTF8.GetString(p.Result);
    Console.WriteLine(response);
});

但调试器仍然说“不!” Data 仍然是 NULL

我确实可以毫无问题地获得 ID。

【问题讨论】:

  • 在旁注中,&lt;data&gt;Hello&lt;/data&gt; 在我看来是 xml,而不是内容类型所暗示的 json

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


【解决方案1】:

如果你想将它作为 JSON 字符串发送,你应该这样做(使用Newtonsoft.Json):

var serialized = JsonConvert.SerializeObject("Hello");
var content = new StringContent(serialized, Encoding.UTF8, "application/json");

FormUrlEncodedContent 几乎是正确的,你要做的就是用一个空名称发送它,就像在 this example 中一样:

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("", "Hello")
});

var response = client.PostAsync("api/ERS?ID=123", content);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    相关资源
    最近更新 更多