MVC WebAPI 的基本使用


1.什么是WebAPI

  Web API是網絡應用程序接口。包含了廣泛的功能,網絡應用通過API接口,可以實現存儲服務、消息服務、計算服務等能力,利用這些能力可以進行開發出強大功能的web應用。

  它可以對接各種客戶端(瀏覽器,移動設備),構建http服務的框架。

2.定義WebAPI接口

  Web API的接口有四種請求方式分別是:GET(獲取一條或者多條數據)、POST(添加數據)、PUT(更新數據)和DELTE(刪除數據)。

  由Web API的路由規則可知,Web API的路由規則只綁定到Controller,所以是根據請求的方式和傳遞的參數來匹配合適的Action,否則將會報錯。

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

  定義主要由以下兩種方式:

  (1)增加Post、Get、Put或者Delete的前綴

    這里的前綴不區分大小寫,系統根據不同的http請求方式找到擁有相應前綴的方法名,具體如下所示:

 

        public IEnumerable<string> GetUsers()
        {
            return new string[] { "value1", "value2" };
        }

  (2)指定特性[HttpPost]、[HttpGet]、[HttpPut]和[HttpDelete]

    這種方式是等效於第一種方式的,但是當同時用了這兩種方式,但是特性和前綴的訪問方式不同的話,以特性為准。

  注意點:

    相同的請求方式下,方法名的命名規則和路由的匹配是沒有關系的,如下:

        [HttpGet]
        public IEnumerable<string> Users()
        {
            return new string[] { "2", "value2" };
        }
        [HttpGet]
        public IEnumerable<string> Cates()
        {
            return new string[] { "1", "value2" };
        }

  這樣通過get方式訪問/api/Home/Users和/api/Home/Cates雖然方法名不同,但是結果卻都是相同的報錯,如下:

<Error>
<Message>發生錯誤。</Message>
<ExceptionMessage>
找到了與該請求匹配的多個操作: 類型 MvcApplication1.Api.HomeController 的 System.Collections.Generic.IEnumerable`1[System.String] Users() 類型 MvcApplication1.Api.HomeController 的 System.Collections.Generic.IEnumerable`1[System.String] Cates()
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
在 System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext) 在 System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext) 在 System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
</StackTrace>
</Error>

  如果將方法稍作修改在Cates增加一個參數id,如下:

        [HttpGet]
        public IEnumerable<string> Users()
        {
            return new string[] { "2", "value2" };
        }
        [HttpGet]
        public IEnumerable<string> Cates(int id)
        {
            return new string[] { "1", "value2" };
        }

  那么訪問/api/Home/Users?id=1或者任意的action如那么訪問/api/Home/xxxx?id=1都可以正確訪問得到如下結果:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>1</string>
<string>value2</string>
</ArrayOfstring>

  但是訪問/api/Home/Users或者/api/Home/Cate的話就會報錯:

<Error>
<Message>請求無效。</Message>
<MessageDetail>
對於“MvcApplication1.Api.HomeController”中方法“System.Collections.Generic.IEnumerable`1[System.String] Cates(Int32)”的不可以為 null 的類型“System.Int32”的參數“id”,參數字典包含一個 null 項。可選參數必須為引用類型、可以為 null 的類型或聲明為可選參數。
</MessageDetail>
</Error>

  綜上所述,Web API的通過請求方式和傳遞的參數來尋找到對應的方法,與方法名無關。

3.參數的傳遞

  (1)[FromUri] 和 [FromBody]

  Web API的參數獲取和普通的Controller有些許不同,參數提交有表單提交和url后面參數傳遞兩種方式,Web API就有對應的着兩種參數的獲取分別[FromBody]獲取表單提交的數據,[FromUri] 獲取url傳參。如下:

 

        [HttpPost]
        public IEnumerable<string> Users([FromUri]User user,[FromUri] int day,[FromBody] string str)
        {
            return new string[] { "2", "value2" };
        }

 

  默認是[FromUri],否則就會獲取指定方式傳遞的參數,可以是類會自動組裝,不允許重復參數的傳遞與接收。

  (2)傳統獲取

  用下面這段代碼可以獲取get請求的數據:

var current = HttpContext.Current.Request;

  但是這樣會有一個問題,就是前面講到的,因為方法沒有參數所以當方法眾多時會有多個參數匹配的方法錯誤。

4.返回值

  Web API返回的數據格式有很多種如IEnumerable<string>(包括json格式和xml格式)、string、void等,但是使用的過程中基本時返回json或者xml格式的數據,所以這里主要講這兩種。Web API可以返回IEnumerable<string>這樣的強類型,

默認返回的時xml格式的數據,在瀏覽器中輸入地址,返回的是xml格式的數據,那怎么返回json格式的呢?

        public HttpResponseMessage GETH(int id)
        {
            string[] strArry = new string[] { "2", "value2" };
            string json = JsonConvert.SerializeObject(strArry);
            //返回純文本text/plain  ,返回json application/json  ,返回xml text/xml
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

  以上的代碼就可以返回json的數據,並且還有其他的返回格式。或者通過更改ajax請求頭的contentType: "application/json; charset=utf-8"來將xml數據轉為json格式。

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM