注冊(cè) 登錄
Office中國(guó)論壇/Access中國(guó)論壇 返回首頁(yè)

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

日志

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

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

一、路由配置

針對(duì)ASP.NET WebAPI,我使用的開(kāi)發(fā)工具是Visual Studio 2012。在新建的WebApi項(xiàng)目中默認(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 為可選項(xiàng)。

二、添加控制器

在項(xiàng)目中添加一個(gè)“包含讀/寫(xiě)操作的 Web API 2 控制器”,命名為“ValueController”,即產(chǎn)生一個(gè) 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)
        {
        }
    }

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

三、初步測(cè)試

運(yùn)行項(xiàng)目,在瀏覽器中訪問(wèn) 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>

而訪問(wèn) 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)。
測(cè)試表明,Web Api 的訪問(wèn)方法為:方法 + 路徑,根據(jù)方法使用路由模板進(jìn)行匹配,本例中的路由模板為 routeTemplate: "api/{controller}/{id}"。
由于是在瀏覽器中的地址欄填入訪問(wèn)地址,故方法為“GET”方法,訪問(wèn)地址根據(jù)路由模板進(jìn)行訪問(wèn) Web Api,例如訪問(wèn) http://localhost:65134/api/value/5
  • http://localhost:65134 為網(wǎng)站地址
  • api 為模板中固定的 api
  • value 為模板中的 controller
  • 5 為模板中的 id,是可選項(xiàng)
:使用瀏覽器測(cè)試 Web Api 并不是一個(gè)好主意,它不太好測(cè)試其它諸如 POST/PUT/DELETE 方法。建議使用大名頂頂?shù)?nbsp;Fiddler 神器,可以構(gòu)造參數(shù)和選擇方法。呵呵,個(gè)人認(rèn)為最好的測(cè)試辦法是
編寫(xiě)一個(gè)網(wǎng)頁(yè),在網(wǎng)頁(yè)中使用 jQuery Ajax 編寫(xiě)一段小程序在 Chrome瀏覽器/360極速瀏覽器中進(jìn)行測(cè)試,因?yàn)?Chrome 的調(diào)試工具箱非常強(qiáng)大。

四、路由機(jī)制

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

評(píng)論 (0 個(gè)評(píng)論)

facelist doodle 涂鴉板

您需要登錄后才可以評(píng)論 登錄 | 注冊(cè)

QQ|站長(zhǎng)郵箱|小黑屋|手機(jī)版|Office中國(guó)/Access中國(guó) ( 粵ICP備10043721號(hào)-1 )  

GMT+8, 2024-10-23 08:27 , Processed in 0.065683 second(s), 17 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

返回頂部