ASP.net MVC - RestSharp POST复杂对象为null

时间:2013-04-16 18:29:51

标签: asp.net-mvc asp.net-web-api

我正在使用ASP.net MVC 4 WebAPI。我有另一个ASP.net MVC应用程序,它发布到Controller中的Web API。但是,当我传递Complex对象时,Complex对象属性在ASP.net MVC 4 Web API中为null。

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();
    }
}

1 个答案:

答案 0 :(得分:0)

将您的GetProdctPrice重命名为PostProdctPrice。

public class ProductsController : ApiController
    {


       // [System.Web.Mvc.HttpPost]
        public string PostProdctPrice(User user) 
        {
            return "hello";
        }
    }

在WebAPI中(当您从APiController继承控制器时),您不需要在方法之上添加[HttpPost]或[HttpGet]属性。任何以Get开头的方法都会自动使用HTTP GET方法进行映射,任何以Post开头的方法都会自动使用HTTP POST方法进行映射。