zoukankan      html  css  js  c++  java
  • WebAPI的路由规则

    1.自定义路由

    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                //1.默认路由
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                //2.自定义路由一:匹配到action
                config.Routes.MapHttpRoute(
                    name: "ActionApi",
                    routeTemplate: "actionapi/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                //3.自定义路由二
                config.Routes.MapHttpRoute(
                    name: "TestApi",
                    routeTemplate: "testapi/{controller}/{ordertype}/{id}",
                    defaults: new { ordertype="aa", id = RouteParameter.Optional }
                );
            }
        }
    

    得到了控制器对象之后,Api引擎通过调用IHttpActionSelector这个接口的SelectAction()方法去匹配action。这个过程主要包括:

    • 解析当前的http请求,得到请求类型(是get、post、put还是delete)
    • 如果路由模板配置了{action},则直接取到url里面的action名称
    • 解析请求的参数

    如果路由模板配置了{action},那么找到对应的action就很简单,如果没有配置action,则会首先匹配请求类型(get/post/put/delete等),然后匹配请求参数,找到对应的action。

            [HttpGet]
            public IHttpActionResult GetById(int id)
            {
                return Ok<string>("Success" + id );
            }
    
            [HttpPost]
            public HttpResponseMessage PostData(int id) 
            {
                return Request.CreateResponse();
            }
    
            [HttpPost]//http://xxx/api/savedata
            public HttpResponseMessage SavaData(ORDER order) 
            {
                return Request.CreateResponse();
            }
    

     2、最简单的特性路由

            [Route("Order/SaveData")]
            [HttpPost]
            public HttpResponseMessage SavaData(ORDER order)
            {
                return Request.CreateResponse();
            }
    
            [Route("ordertype/{id}/order")]
            [HttpGet]
            public IHttpActionResult GetById(int id)
            {
                return Ok<string>("Success" + id );
            }
    

    特性路由的目的是为了解决我们公共路由模板引擎解决不了的问题。一个action定义了特性路由之后,就能通过特性路由上面的路由规则找,特性路由的规则可以使用“{}”占位符动态传递参数,比如我们有这样一个特性路由

  • 相关阅读:
    CF1221D Make The Fence Great Again
    HDU.1536.S-Nim(博弈论 Nim)
    HDU.1848.Fibonacci again and again(博弈论 Nim)
    POJ.1704.Georgia and Bob(博弈论 Nim)
    洛谷.2197.nim游戏(博弈论 Nim)
    博弈论基础——巴什博弈
    SPOJ.104.Highways([模板]Matrix Tree定理 生成树计数)
    BZOJ.4289.PA2012 Tax(思路 Dijkstra)
    BZOJ.4753.[JSOI2016]最佳团体(01分数规划 树形背包DP)
    图论
  • 原文地址:https://www.cnblogs.com/l1pe1/p/7927602.html
Copyright © 2011-2022 走看看