【发布时间】: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。
【问题讨论】:
-
在旁注中,
<data>Hello</data>在我看来是 xml,而不是内容类型所暗示的 json
标签: c# asp.net-web-api httpclient