【发布时间】:2015-05-31 04:32:12
【问题描述】:
我正在尝试将带有 json 内容的请求发送到 web api,这些值不会自动映射到我的对象。
这是导致 null 的我的 API 操作。
[HttpPost]
public IEnumerable<string> GetCustomerByName([FromBody] Request_GetCustomerByName request)
{
// Some Action
}
如果我像下面这样更改参数,我可以正常接收数据。所以我想知道为什么我的 json 字符串不会自动映射到对象。
[HttpPost]
public IEnumerable<string> GetCustomerByName([FromBody] dynamic request)
{
// Some action
}
这是我发送请求的地方。
public ActionResult Index()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:40175/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Request_GetCustomerByName r = new Request_GetCustomerByName()
{
Customer = new Customer() { CustomerId = 1, CustomerName = "Name" },
RequestBase = new RequestBase() { Somefield="123"}
};
var json = new JavaScriptSerializer().Serialize(r);
HttpResponseMessage response = client.PostAsJsonAsync("api/values/GetCustomerByName", json).Result;
if (response.IsSuccessStatusCode)
{
var resVal = response.Content.ReadAsStringAsync().Result;
Response.Write(resVal);
}
}
return View();
}
谢谢,我在这一点上卡了几个小时...
【问题讨论】:
-
没什么可继续的。您能否同时发布
Request_GetCustomerByName类的定义和正在发送的 JSON 样本?
标签: asp.net json asp.net-mvc asp.net-web-api