注冊 登錄
Office中國論壇/Access中國論壇 返回首頁

zhuyiwen的個人空間 http://m.mzhfr.cn/?625 [收藏] [復(fù)制] [分享] [RSS]

日志

ASP.NET WebApi 路由匹配及參數(shù)傳遞

已有 1822 次閱讀2021-9-16 09:52 |個人分類:ASP.NET| WebApi, 路由, 參數(shù)傳遞

一、路由配置

針對ASP.NET WebAPI,我使用的開發(fā)工具是Visual Studio 2012。在新建的WebApi項目中默認(rèn)的路由配置為:
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
             // Web API routes
            config.MapHttpAttributeRoutes();

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

從其中可以得到l默認(rèn)路由匹配模板:routeTemplate: "api/{controller}/{id}"。其中 defaults: new { id = RouteParameter.Optional } 定義 id 為可選項。

二、添加控制器

在項目中添加一個“包含讀/寫操作的 Web API 2 控制器”,命名為“ValueController”,即產(chǎn)生一個 ValueController.cs 的文件,其內(nèi)容為
    public class ValueController ApiController
    {
        // GET api/value
        public IEnumerable<string> Get()
        {
            return new string[] { "value1""value2" };
        }

        // GET api/value/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/value
        public void Post([FromBody]string value)
        {
        }

        // PUT api/value/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/value/5
        public void Delete(int id)
        {
        }
    }

這是一個控制器模板,其控制器的名稱為“Value”,它與“ValueController”是一種約定俗成的關(guān)系,一看便知,“Value”控制器的類為“ValueController”。

三、初步測試

運行項目,在瀏覽器中訪問 http://localhost:65134/api/value,可得到如下結(jié)果:(注:使用Chrome瀏覽器/360極速瀏覽器)
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <string>value1</string>
    <string>value2</string>
</ArrayOfstring>

而訪問 http://localhost:65134/api/value/5 得到的結(jié)果如下:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">value</string>
呵呵,可以看出,http://localhost:65134/api/value 路由到了 public IEnumerable<string> Get() 方法,而 http://localhost:65134/api/value/5 路由到了 public string Get(int id)。
測試表明,Web Api 的訪問方法為:方法 + 路徑,根據(jù)方法使用路由模板進行匹配,本例中的路由模板為 routeTemplate: "api/{controller}/{id}"
由于是在瀏覽器中的地址欄填入訪問地址,故方法為“GET”方法,訪問地址根據(jù)路由模板進行訪問 Web Api,例如訪問 http://localhost:65134/api/value/5
  • http://localhost:65134 為網(wǎng)站地址
  • api 為模板中固定的 api
  • value 為模板中的 controller
  • 5 為模板中的 id,是可選項
:使用瀏覽器測試 Web Api 并不是一個好主意,它不太好測試其它諸如 POST/PUT/DELETE 方法。建議使用大名頂頂?shù)?nbsp;Fiddler 神器,可以構(gòu)造參數(shù)和選擇方法。呵呵,個人認(rèn)為最好的測試辦法是
編寫一個網(wǎng)頁,在網(wǎng)頁中使用 jQuery Ajax 編寫一段小程序在 Chrome瀏覽器/360極速瀏覽器中進行測試,因為 Chrome 的調(diào)試工具箱非常強大。

四、路由機制

例如訪問 http://localhost:65134/api/value/5,首先 Web Api 匹配路徑中的 "api" 確定是 Web Api 訪問,再匹配 “value” 找到控制器 “ValueController”,再根據(jù)訪問方法“GET”,在控制器類中匹配定義為“HttpGet”的方法,在本例中有兩個,public IEnumerable<string> Get() 和 public string Get(int id),最終根據(jù)“5”來匹配有參數(shù)的 public string Get(int id)方法。它不是根據(jù)控制器方法名稱來匹配的是不是很郁悶?
:約定俗成,控制器中方法名稱以“Get”開頭的方法默認(rèn)為“HttpGet”方法,以此類推,“Post”開頭的方法默認(rèn)為“HttpPost”方法...,它們不必注明[HttpGet]/[HttpPost]...。否則,必須方法定義的上一行用[HttpGet]/[HttpPost]...注明方法。呵呵,ASP.NET Web Api 和 Mvc 中有很多約定俗成規(guī)定。

評論 (0 個評論)

facelist doodle 涂鴉板

您需要登錄后才可以評論 登錄 | 注冊

QQ|站長郵箱|小黑屋|手機版|Office中國/Access中國 ( 粵ICP備10043721號-1 )  

GMT+8, 2025-7-13 09:08 , Processed in 0.256191 second(s), 17 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

返回頂部