定义web api post方法的正确方法

时间:2014-07-18 11:16:15

标签: asp.net-web-api restsharp

我有一个.NET Web Api REST服务器,它有一个类客户的控制器,它有一个这样的post方法:

public HttpResponseMessage PostCustomer()
{
    //getting the data in the request body****
    return new HttpResponseMessage(HttpStatusCode.Created);
}

这是我的班级:

 class Customer
{
    public Customer(string name, string tell, string pass, string add)
    {
        FnameLname = name;
        Address = add;
        Password = pass;
        AccountNumber = tell;
    }

    public int CustomerId { get; set; }
    public string AccountNumber { get; set; }
    public string Password { get; set; }
    public string Address { get; set; }
    public string FnameLname { get; set; }
}

我有一个C#表单应用程序使用者,我使用RESTSharp这样做。 我试图做一个帖子请求来创建一个客户,但我没有运气设置它。 这是我到目前为止所得到的:

{
      Customer newc=new Customer(...); 
      var client = new RestClient("http://192.168.137.1:9090/");
      var request = new RestRequest("api/Customer",Method.POST);
      request.RequestFormat = DataFormat.Json;
      request.AddObject(newc);
      var response = client.Execute(request);
}

但它不起作用。 我不知道我的控制器方法是错误还是请求错误。

1 个答案:

答案 0 :(得分:0)

您的Post方法需要接受Customer参数,以便WebAPI尝试将请求正文中的JSON绑定到customer参数

public HttpResponseMessage PostCustomer(Customer customer)
{ ... }