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

  • 相关阅读:
    闲话: 恭喜园子里的MVP一下, 同时问所有奋斗在技术领域的兄弟过节好~
    随便说两句: 表设计兼一些设计分析的讨论
    是他妈傻子写的么?
    Utility Wish List
    我终于有个偶像了
    也论标准: 统一是啥好事情?
    linux 编程学习笔记(1)搭建c(c++)开发环境
    Immutable Collections(2)ImmutableList<T>实现原理.(上)
    托管代码的进程注入&CLR宿主
    .NET安全揭秘系列博文索引
  • 原文地址:https://www.cnblogs.com/min-min-min/p/7777036.html
Copyright © 2011-2022 走看看