webAPI路由的使用

根據WEBAPI的路由規則,在實際項目當中有二種用法,前端

一:webAPI.Config裏面爲 web

config.MapHttpAttributeRoutes();

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

控制器裏面加上【HttpGet,HttpPOST】認證,並將接口使用路由暴露出來,寫法有兩種spa

(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裏面爲 get

config.MapHttpAttributeRoutes();

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

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

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

 

兩種狀況,若是不使用【httpPost】【httpGet】,後臺會根據前臺的請求類型匹配控制器的action,如get請求,無論前臺訪問哪一個接口,後臺均匹配以Get開頭的控制器actionio

相關文章
相關標籤/搜索