如何将查询字符串参数传递给ASP.NET Web API 2 [英] How to pass query string parameter to asp.net web api 2

查看:58
本文介绍了如何将查询字符串参数传递给ASP.NET Web API 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

这是CustomerRequest类

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.

谢谢

推荐答案

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

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

如果要使"id"为可选,则可以使方法签名看起来像这样:

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)

如果未在URL中传递ID,则默认情况下会将ID设置为0.这样您就可以像最初一样访问您的URL:

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

这篇关于如何将查询字符串参数传递给ASP.NET Web API 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆