zoukankan      html  css  js  c++  java
  • 使用ASP.Net WebAPI构建REST服务(四)——参数绑定

    默认绑定方式

    WebAPI把参数分成了简单类型和复杂类型:

    • 简单类型主要包括CLR的primitive types,(int、double、bool等),系统内置的几个strcut类型(TimeSpan、Guid等)以及string。对于简单类型的参数,默认从URI中获取。
    • 复杂类型的数据也可以直接作为参数传入进来,系统使用media-type formatter进行解析后传给服务函数。对于复杂类型,默认从正文中获取,

    例如,对于如下函数

        HttpResponseMessage Put(int id, Product item)

    其id默认从url中获取,其item默认从正文中获取。

    使用 [FromUri] 标记从URI中绑定参数

    我们可以使用 [FromUri] 标记强制从URI中绑定参数,例如

        public class GeoPoint
        {
            public double Latitude { get; set; }
            public double Longitude { get; set; }
        }

        public ValuesController : ApiController
        {
            public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
        }

    这样,Get参数就是从URI中获取了。需要注意的是,此时我们必须将GeoPoint的属性在URI中传入: http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989 。这种默认的序列化方式比较冗长,我们也可以自定义反序列化格式为类似这样的形式:http://localhost/api/values/?location=47.678558,-122.130989具体方法请参看参考文档 Type Converters 的一节。

     

    使用 [FromBody] 标记从正文中绑定参数

    同样,我们可以使用 [FromBody] 标记强制从正文中绑定参数,例如

        public HttpResponseMessage Post([FromBody] string name)

    此时,我们则

        POST http://localhost:5076/api/values HTTP/1.1
        User-Agent: Fiddler
        Host: localhost:5076
        Content-Type: application/json
        Content-Length: 7

        "Alice"

    需要注意的是这儿的Content-Type必须和正文的序列化方式一致,这儿使用的是json序列化,因此类型是application/json。系统自动使用Media Formatters将其转换为目标对象。

     

    绑定多个参数

    前面介绍的方式中,只能从URI中绑定一个参数,虽然可以通过传入复杂类型解决多参数的问题,但很多时候不如在URI中来得直接。此时,我们则可以使用前面介绍的特性路由来实现多参的绑定,例如:

        [Route("api/{controller}/{year}/{month}/{day}")]
        public string Get(int year, int month, int day)
        {
            return string.Join(",", year, month, day);
        }

     

    参考文档: http://www.asp.net/web-api/overview/formats-and-model-binding

  • 相关阅读:
    转载:Python十分钟入门
    Think Python: How to Think Like a Computer Scientist
    LeetCode(34):搜索范围
    LeetCode(33):搜索旋转排序数组
    LeetCode(32):最长有效括号
    LeetCode(31): 下一个排列
    LeetCode(30):与所有单词相关联的字串
    LeetCode(29): 两数相除
    LeetCode(28): 实现strStr()
    LeetCode(27): 移除元素
  • 原文地址:https://www.cnblogs.com/TianFang/p/3720053.html
Copyright © 2011-2022 走看看