好吧......我在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);
});
但调试人员仍然说“不!” Data
仍然是NULL
。
我确实得到了ID没问题。
如果要将其作为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);