asp.net Web API

Get:

1、Get参数传递的本质是url字符串拼接;
2、url字符串长度受限制;
3、Get参数传递在Http请求头部传递,而不支持Request-Body传递;
4、Get类型的方法支持参数为基本类型,不支持实体类型;
5、Get类型的方法命名,应尽量采用“Get+方法名”的命名方式,且习惯性地在方法前加上[HttpGet特性];
6、实参与形参的匹配,遵循路由规则;
7、Get对应DB的Select操作,从这一点来理解,就知道为什么Http不支持实体对象传递的合理性了,因为一般情况,我们都是通过简单的字段查询信息(对应基本类型)

        //api/Person
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        //http://localhost:27653/api/person/25
        //[Route("GetID")]
        [Route("api/Person/{id}")]//如果在这里设置了路由,那么就不会再执行webAPIConfig.cs中的路由了。
        public string Get(int id)
        {
            return "vichin" + id;
        }
        //api/Person?phoneNum=186

        //http://localhost:27653/api/person?phoneNum=25
        //多个重载的时候,可以通过URL传参的形式来指定所要调用的方法。
        public string GetPhoneNum(int phoneNum)
        {
            return phoneNum.ToString();
        }

        //api/Person?name=vichin
        public int Get(string name)
        {
            return name.Length;
        }

 

Post:

1、Post参数传递本身是在Request-Body内传递,而Get参数传递本质是url拼接;
2、Post参数传递不是key/value形式,而Get参数是key/value形式;
3、Post传递参数时,无论是单个参数还是对象,均借助[FromBody] 特性(当然,某些情况去掉[FromBody] 特性也可把值传递进去,但为了规范化,尽量加上该特性);
4、Post没长度限制,而Get有长度限制(一般为1024b);
5、Post相对Get,较安全;
6、Post操作相当于DB的Insert操作;

        [HttpPost]
        public string Post([FromBody]string value, string value1)//[FromBody] string value
        {
            return "Post 请求,value= " + value;
        }

        [HttpPost]
        public string PostDynamic([FromBody]Product product)//[FromBody] string value
        {
            return "PostDynamic 请求,value= " + product.ProductName;
        }

        public string Put(int id, [FromBody] string value)//只有有一个参数用FromBody来修饰
        {
            return "Put 请求,value=" + value + ",id=" + id;
        }
        public string Delete(int id)
        {
            return "Delte请求, id:";
        }

如果使用Post请求,那么就需要每个方法都声明一个参数对应的类(即使只有一个参数),参数前标注[FromBody],参数少的话麻烦,如果使用Get请求,那么都可以,但是需要注意防范缓存(HttpClient,ajax等需要禁用掉缓存)。

            $("#btn").click(function () {
                $.ajax({
                    type: "Post",
                    url: "http://localhost:27653/api/person",
                    data: { "": "value" },//post请求,不需要key
                    success: function (res) {
                        alert(res);
                    },
                    error: function (msg) {
                        alert(msg.responseText);
                    }
                });
            });

            //GET请求可以在url传参也可以将data中,已KEY:VALUE的形式进行传参。(其实在Chrome中能够发现,最终也是变成了URL传参)
            //    $.ajax({
            //        type: "Get",
            //        url: "/api/Default/ProductDetails",
            //        data: { "productDetail": JSON.stringify({ "ProductName": "YaGao", "ProductCode": "JX80869", "ProductPrice": 40.5 }) }
            //    })
            //})

            //dynamic单个参数传递
            $("#btn1").click(function () {
                $.ajax({
                    type: "Post",
                    url: "http://localhost:27653/api/person",
                    data: { "ProductCode": "JX00036", "ProductName": "YaGao", "ProductPrice": 20.5 },
                    success: function (res) {
                        alert(res);
                    },
                    error: function (msg) {
                        alert(msg.responseText);
                    }
                });
            });

            var list_ProductDetail = [
                { "ProductCode": "JX00031", "ProductName": "ToothPaste", "ProductPrice": "20.5" },
                { "ProductCode": "JX00032", "ProductName": "ToothBrush ", "ProductPrice": "18.9" },
                { "ProductCode": "JX00033", "ProductName": "Pen", "ProductPrice": "199.9" },
                { "ProductCode": "JX00034", "ProductName": "computer", "ProductPrice": "15000.5" }
            ]

            $.ajax({
                type: "Post",
                contentType: 'application/json',
                url: "/api/Default/PostParamToProducts",
                data: JSON.stringify(list_ProductDetail)
            });

            var arr = ["a", "b", "c", "d"];
            data: JSON.stringify(arr)

 

其他的操作如put delete大体上与post请求差不多。

 

路由:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();//特性路由

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

如果在路由中配置了action(routeTemplate: "api/{controller}/{action}/{id}"), MVC风格的路由。那么请求的网址将会是api/person/GetName/id。

 

//路由前缀
[RoutePrefix("api/Product")]

//重写路由前缀
[Route("~/api/authors/{authorId:int}/books")]

 路由约束

约束描述示例
alpha 匹配大写或小写字符 (-z、 A-Z) {x: alpha}
bool 匹配一个布尔值。 {x: bool}
datetime 匹配项DateTime值。 {x: datetime}
decimal 匹配十进制值。 {x:decimal}
double 与 64 位浮点值匹配。 {x:double}
float 与 32 位浮点值匹配。 {x: float}
guid 匹配的 GUID 值。 {x: guid}
int 与 32 位整数值匹配。 {x: int}
length 与具有指定长度或长度的指定范围内的字符串匹配。 {x:length(6)} {x:length(1,20)}
long 与 64 位整数值匹配。 {x: 长时间}
max 匹配一个整数,其最大值。 {x:max(10)}
maxlength 与最大长度的字符串匹配。 {x:maxlength(10)}
min 匹配一个整数,其最小值。 {x: min(10)}
minlength 与最小长度的字符串相匹配。 {x: minlength(10)}
range 一个整数值的范围内的匹配项。 {x: range(10,50)}
正则表达式 与正则表达式匹配。 {x:regex(^\d{3}-\d{3}-\d{4}$)}
将多个约束应用于参数,用冒号分隔。

[Route("users/{id:int:min(1)}")] public User GetUserById(int id) { ... }

 先认真 后授权。使用Anonymous 可以忽略身份认证

posted @ 2019-11-25 16:54  水墨晨诗  阅读(430)  评论(0编辑  收藏  举报