[英]HttpClient send null POST data
好吧...我在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,沒有問題。
如果要將其作為JSON字符串發送,則應執行此操作(使用Newtonsoft.Json ):
var serialized = JsonConvert.SerializeObject("Hello");
var content = new StringContent(serialized, Encoding.UTF8, "application/json");
使用FormUrlEncodedContent
幾乎可以正確地FormUrlEncodedContent
它,您要做的就是使用一個空名稱發送它,例如以下示例 :
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "Hello")
});
var response = client.PostAsync("api/ERS?ID=123", content);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.