2013-04-16 69 views
2

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

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

是否确定,您的请求有产品和用户的详细信息。请使用提琴手并检查您的请求主体 –

+0

如果您不使用类似于:request.AddParameter(“User”,user) –

回答

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方法进行映射。