HttpClient 发送空的 POST 数据

Izi*_*kon 1 c# httpclient asp.net-web-api

嗯...我在 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我给它写了一个小测试:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

client.DefaultRequestHeaders
                           .Accept
                           .Add(new MediaTypeWithQualityHeaderValue("application/json"));
Run Code Online (Sandbox Code Playgroud)

尽管如此NULL,我也将内容替换为:

var values = new Dictionary<string, string>();
values.Add("Data", "Data");
var content = new FormUrlEncodedContent(values);
Run Code Online (Sandbox Code Playgroud)

还是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);
});
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*rio 5

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

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

你几乎搞定了FormUrlEncodedContent,你必须做的是用一个空名称发送它,就像在这个例子中一样

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

var response = client.PostAsync("api/ERS?ID=123", content);
Run Code Online (Sandbox Code Playgroud)