如何将查询字符串参数传递给asp.net web api 2

时间:2015-10-06 14:01:10

标签: entity-framework c#-4.0 visual-studio-2013 asp.net-web-api2

如何将超过1个参数作为查询字符串的一部分传递给我的asp.net web api 2.

这是我的asp.net web api 2方法,我无法弄清楚如何装饰这个方法,以便它接受id和一个复杂的类型,即CustomerRequest,我想使用类似< / p>

  

http://localhost/api/Customer/?Mobile0012565987&Email=abcxyz.com&IsEmailVerified=true

[ResponseType(typeof(Customer))]
public IHttpActionResult GetCustomer(long id, [FromUri]CustomerRequest request)
        {
            var customer = db.Customers.Find(request.CustomerId);

            if (customer == null)
            {
                return NotFound();
            }

            return Ok(customer);
        }

这是CustomerRequest类

  public class CustomerRequest
    {
        public string Mobile { get; set; }
        public string Email { get; set; }         
        public Nullable<bool> IsEmailVerified { get; set; }    
    }

如果有更好的方法,请告诉我。

由于

1 个答案:

答案 0 :(得分:0)

根据您的代码,您还需要传递'id',如下所示:

http://localhost/api/Customer/?id=12345&Mobile=0012565987&Email=abcxyz.com&IsEmailVerified=true

如果你想让'id'可选,你可以使你的方法签名看起来像这样:

public IHttpActionResult GetCustomer([FromUri]CustomerRequest request, long id = 0)

如果你没有在URL中传递id,默认情况下会将id设置为0。因此,您可以像以前一样访问您的网址:

http://localhost/api/Customer/?Mobile=0012565987&Email=abcxyz.com&IsEmailVerified=true