How to pass query string parameter to asp.net web api 2

女生的网名这么多〃 提交于 2019-12-11 18:28:52

问题


How can I pass more than 1 parameters as part of query string to my asp.net web api 2.

This is my asp.net web api 2 method, I am not able to figure out that how can I decorate this method so that it accepts the id and a complex type which is CustomerRequest, I want to use Url something like

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

This is CustomerRequest class

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

Otherwise pleaase guide me if there is a better way to do it.

Thanks


回答1:


Based on your code, you need to pass 'id' as well, like this:

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

if you want to make 'id' optional, you can make your method signature look like this:

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

this will set id to 0 by default, if you dont pass it in the URL. So you will be able to access your URL like you originally did:

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



来源:https://stackoverflow.com/questions/32971977/how-to-pass-query-string-parameter-to-asp-net-web-api-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!