zoukankan      html  css  js  c++  java
  • webAPI路由的使用

    根据WEBAPI的路由规则,在实际项目当中有二种用法,

    一:webAPI.Config里面为 

    config.MapHttpAttributeRoutes();

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

    控制器里面加上【HttpGet,HttpPOST】认证,并将接口使用路由暴露出来,写法有两种

    (1)在控制器上面加上路由前缀,action之前加上action名字从而将整个路由暴露出来,方便前端调用

       [RoutePrefix("api/Values")]
        public class ValuesController : ApiController
        {
            // GET api/values
            [HttpGet]
            [Route("testLog")]
            public IEnumerable<string> testLog()
            {
                LogHelper.WriteLog("hello can you hear me~");

                return new string[] { "value1", "value2" };
            }
    (2)直接在action之前加上整个路由路径从而将整个路由暴露出来
        public class ValuesController : ApiController
        {
            // GET api/values
            [HttpGet]
            [Route("api/Values/testLog")]
            public IEnumerable<string> testLog()
            {
                LogHelper.WriteLog("hello can you hear me~");

                return new string[] { "value1", "value2" };
            }

    二:webAPI.Config里面为 

    config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    控制器里面加上【HttpGet,HttpPOST】认证, 不需要使用路由暴露接口

           [HttpGet]
            public IEnumerable<string> testLog()
            {
                LogHelper.WriteLog("hello can you hear me~");

                return new string[] { "value1", "value2" };
            }

    两种情况,如果不使用【httpPost】【httpGet】,后台会根据前台的请求类型匹配控制器的action,如get请求,不管前台访问哪个接口,后台均匹配以Get开头的控制器action

  • 相关阅读:
    【转帖】电阻电容的封装
    FT2232H的MCU Host Bus Emulation 模式
    google cpp style guide
    CY7C131 BUSY信号线的接法
    有关沟通的常识
    关于for和foreach,兼顾效率与安全
    绩效面谈中处理分歧的小窍门
    SQL 合并列值和拆分列值
    如何保护.net中的dll文件(防止破解、反编译dll)(转)
    .NET框架图解之五:System.Reflection
  • 原文地址:https://www.cnblogs.com/min-min-min/p/7777036.html
Copyright © 2011-2022 走看看