如何为Web API添加新操作?

时间:2014-01-18 02:27:01

标签: c#-4.0 asp.net-web-api

我是一个Web API初学者,所以这里。我已经定义了我的CustomersController:

public class CustomersController : ApiController
{
    public Customer Get(int id)
    {
        var customer = CustomerDataSource.customerData.Where(c => c.id == id).First();
        return customer;
    }

    public List<Customer> Get(string search)
    {
        var list = CustomerDataSource.customerData;
        return list;
    }


}

CustomerDataSource.customerData返回对象列表:

public static List<Customer> customerData
{
    get
    {
        Customer customer1 = new Customer() {id=1, name = "Bert", address = "London"};
        customer1.nicknames= new string[]{"jack","bart"};

        Customer customer2 = new Customer() { id=2,name = "Jon", address = "New York" };
        customer2.nicknames= new string[]{"ed","fred"};

        List<Customer> listCustomers = new List<Customer>();
        listCustomers.Add(customer1);
        listCustomers.Add(customer2);

        return listCustomers;
    }
}
public class Customer
{   
        public int id { get; set; }
        public string name { get; set; }
        public string address { get; set; }
        public string[] nicknames { get; set; }
}

我已经定义了一个Get方法,它返回Customer的所有实例。如果需要我还可以在我的数据源中搜索,我还可以添加额外的搜索参数。假设我想做另一个例如排序的任务。我试过了:

public List<Customer> Get(string sort)
{
  var list = CustomerDataSource.customerData;
  return list;
}

但是这不会编译:

'CustomersController' already defines a member called 'Get' with the same parameter

问题是如何重构我的控制器,以便在保持Web API接口的同时传递searchargument和sortargument?

1 个答案:

答案 0 :(得分:0)

根据T.S.的建议,您可以向控制器添加post方法并发布JSON模型,如下所示。当然,您必须构建CustomerDataSource.GetCustomerData方法。

public class CustomerSearchModel
{
    public string Search { get; set; }
    public string Sort { get; set; }
    public string Foo { get; set; }
}



public class CustomersController : ApiController
{
    public List<Customer> Get()
    {
        //If you wanted to just parse the querystring, do it here with Request.RequestUri.Query
        return CustomerDataSource.customerData;
    }

    public Customer Get(int id)
    {
        var customer = CustomerDataSource.customerData.Where(c => c.id == id).First();
        return customer;
    }

    public List<Customer> Post(CustomerSearchModel model)
    {
        return CustomerDataSource.GetCustomerData(model);
    }
}

如果您需要从URI传入模型,请添加[FromUri]:

 public List<Customer> Post([FromUri] CustomerSearchModel model)