我正在使用 ASP.net MVC 4 WebAPI。我有另一个 ASP.net MVC 应用程序,它发布到 Controller 中的 Web API。但是,当我传递复杂对象时,复杂对象属性在 ASP.net MVC 4 Web API 中变为空。
WEB API 代码
public class User
{
public string Name { get; set; }
public Product Product { get; set; }
}
public class Product
{
public int Age { get; set; }
}
public class ProductsController : ApiController
{
[HttpPost]
public string GetProdctPrice([FromBody]User user) // user object is null
{
return "hello";
}
}
ASP.NET MVC 消费者代码
public class User
{
public string Name { get; set; }
public Product Product { get; set; }
}
public class Product
{
public int Age { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var user = new User()
{
Name = "Headphone",
Product = new Product() { Age = 33 }
};
var client = new RestClient();
client.BaseUrl = "http://localhost:56013/api/";
var request = new RestRequest();
request.Method = Method.POST;
request.Resource = "/Products/GetProdctPrice";
request.AddObject(user);
IRestResponse response = client.Execute(request);
ViewBag.Message = response.Content;
return View();
}
}