【问题标题】:How to pass query string parameter to asp.net web api 2如何将查询字符串参数传递给asp.net web api 2
【发布时间】:2015-10-06 14:01:09
【问题描述】:

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

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

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

否则,如果有更好的方法,请指导我。

谢谢

【问题讨论】:

  • 你能显示你的路由表吗?

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


【解决方案1】:

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

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

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

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

这将默认设置 id 为 0,如果你没有在 URL 中传递它。这样您就可以像原来一样访问您的 URL:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多