- 确认接收数据的 action 是否正确设置了接收类型为 JSON:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
// ...
}
- 确认发送数据的 action 中 MediaType 是否设置为 JSON:
[HttpPost]
public ActionResult SendData()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
MyModel model = new MyModel();
// 设置 model 的属性值
// ...
HttpResponseMessage response = client.PostAsJsonAsync("url", model).Result;
// ...
}
- 确认 MyModel 是否正确设置为 JSON 格式:
public class MyModel
{
public string Name { get; set; }
public int Age { get; set; }
// 需要添加无参数的构造函数
public MyModel() { }
}
- 如果仍然无法发送 JSON 数据,可以尝试通过手动序列化为 JSON 字符串发送:
string json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("url", content).Result;
- 如果还有问题,可以查看错误日志或者进行调试。