HttpClient发送空POST数据

时间:2017-12-25 14:34:15

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

嗯......我在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中的参数NULL上获得Data

我尝试将这些行添加到测试人员中:

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);
});

但调试人员仍在说“不!”#39; Data仍为NULL

我确实没有问题。

1 个答案:

答案 0 :(得分:4)

如果要将其作为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);