小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Asp.netCore RESTful WebApi 小結(jié)

 行者花雕 2021-03-28

上篇文章記錄了WebApi的概念以及簡(jiǎn)單的認(rèn)知WebApi ,今天來(lái)探究下它的適用場(chǎng)景以及怎么去用它。

  先簡(jiǎn)單聊一下WebApi與用得比較多的WCF、WebService各自的特點(diǎn):

  一、WebService是一種可以接收從Internet或者Intranet上的其它系統(tǒng)中傳遞過(guò)來(lái)的請(qǐng)求,輕量級(jí)的獨(dú)立的通訊技術(shù),它的特點(diǎn)有:

    1、基于SOAP協(xié)議的,數(shù)據(jù)格式是XML;

    2、web Service 最大的優(yōu)勢(shì)便是跨平臺(tái)的可互操作性;

    3、支持Http協(xié)議Xml技術(shù)的設(shè)備即可擁有并且訪問(wèn)web Service,但只能部署在IIS上 ;

    4、一些只需要與本機(jī)上的其余程序通訊的應(yīng)用程序則不適合用web Service,理由并非技術(shù)上無(wú)法實(shí)現(xiàn),而是消耗過(guò)大沒(méi)有任何好處。

  二、WCF是提供統(tǒng)一的,可用于建立安全、可靠的面向服務(wù)的應(yīng)用的高效開(kāi)發(fā)平臺(tái),其特點(diǎn)有:

    1、基于SOAP協(xié)議的,數(shù)據(jù)格式是XML;

    2、可以支持各種各樣的協(xié)議,比如TCP,HTTP,HTTPS,Json等;

    3、與其前輩web Service相比,WCF不僅可以部署在IIS上還可以部署在應(yīng)用程序中或者Windows服務(wù)中;

    4、只要支持標(biāo)準(zhǔn)的web service,可以跨進(jìn)程、跨機(jī)器甚至于跨平臺(tái)的通信。

  三、WebApi的特點(diǎn):

    1、需要通過(guò)URI信息來(lái)指定端點(diǎn),每一個(gè)URI代表1種資源;

    2、可通過(guò)不同的http動(dòng)作表達(dá)不同的含義,客戶端使用GET、POST、PUT、DELETE4個(gè)表示操作方式的動(dòng)詞對(duì)服務(wù)端資源進(jìn)行操作:GET用來(lái)獲取資源,POST用來(lái)新建資源(也可以用于更新資源),PUT用來(lái)更新資源,DELETE用來(lái)刪除資源;

    3、通過(guò)請(qǐng)求來(lái)實(shí)現(xiàn)對(duì)資源的資源,資源的表現(xiàn)形式大多是XML或者HTML(亦或其它),請(qǐng)求的回復(fù)通過(guò)Http Status Code表達(dá)不同含義,并且客戶端可以通過(guò)Accept header來(lái)與服務(wù)器協(xié)商格式,例如希望服務(wù)器返回JSON格式還是XML格式亦或者其他擴(kuò)展格式;

    4、支持跨平臺(tái)、CORS跨域調(diào)用WebApi,如通過(guò)前端js或者直接在后臺(tái)調(diào)用它,部署時(shí)支持Self-host或者IIS。;

    5、客戶端與服務(wù)端之間的交互在請(qǐng)求之間是無(wú)狀態(tài)的,從客戶端到服務(wù)端的每個(gè)請(qǐng)求都必須包含理解請(qǐng)求所必需的信息。

  聊完它們的特點(diǎn),那么如何物盡其用呢?(參考鏈接:https://blog.csdn.net/u013043518/java/article/details/51793294)

    1、當(dāng)你想創(chuàng)建一個(gè)支持消息、消息隊(duì)列、雙工通信的服務(wù)時(shí),你應(yīng)該選擇WCF

    2、當(dāng)你想創(chuàng)建一個(gè)服務(wù),可以用更快速的傳輸通道時(shí),像TCP、NamedPipes或者甚至是UDP(在WCF4.5中),在其他傳輸通道不可用的時(shí)候也可以支持HTTP。

    3、當(dāng)你想創(chuàng)建一個(gè)基于HTTP的面向資源的服務(wù)并且可以使用HTTP的全部特征時(shí)(比如URIs、request/response頭,緩存,版本控制,多種內(nèi)容格式),你應(yīng)該選擇WebAPI

    4、當(dāng)你想讓你的服務(wù)用于瀏覽器、手機(jī)、iPhone和平板電腦時(shí),你應(yīng)該選擇Web API

   前面在聊WebApi特點(diǎn)的時(shí)候有提到可以通過(guò)前端或者在后臺(tái)去調(diào)用它,看下具體如何調(diào)用:

    例1: 通過(guò)HttpClient類調(diào)Api。在Web API發(fā)布的同時(shí),.NET提供了兩個(gè)程序集:System.Net.Http和System.Net.Http.Formatting。這兩個(gè)程序集中最核心的類是HttpClient (在這里只討論如何調(diào)WebApi,思路為打磨一個(gè)通用的工具類,其余部分各位看官自由發(fā)揮):

 1 public class CallAPI 2 { 3 private static string uri = "http://localhost:5000/"; 4 private HttpClient client = new HttpClient(); 5  6 /// <summary> 7 /// 簡(jiǎn)單查詢 8 /// </summary> 9 /// <param name="resource">目標(biāo)資源</param>10 public void GetData(string resource)11 {12   client.BaseAddress = new Uri(uri);13 14   // 為JSON格式添加一個(gè)Accept報(bào)頭15   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));16   HttpResponseMessage responseMessage = client.GetAsync(resource).Result;//獲取查詢結(jié)果17   if (responseMessage.IsSuccessStatusCode)18   {19     var ds = responseMessage.Content.ReadAsStringAsync().Result;20     string content = JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);//轉(zhuǎn)換為你想要的格式如xml,json等,定義通用的轉(zhuǎn)換類這里就不介紹了,請(qǐng)自行打造21   }22 }23 24 /// <summary>25 /// 帶參查詢26 /// </summary>27 /// <param name="resource">目標(biāo)資源</param>28 /// <param name="id">ID</param>29 public void GetDataWithParam(string resource)30 {31   client.BaseAddress = new Uri(uri);32 33   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));34   HttpResponseMessage responseMessage = client.GetAsync(resource).Result;35   if (responseMessage.IsSuccessStatusCode)36   {37     var ds = responseMessage.Content.ReadAsStringAsync().Result;38     string content = JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);39   }40 41 }42 43 44 /// <summary>45 /// put請(qǐng)求更新資源46 /// </summary>47 /// <param name="resource"></param>48 /// <returns></returns>49 public bool PutData(string resource)50 {51   bool bol = false;52   //創(chuàng)建和webapi對(duì)應(yīng)的類53   var content = new FormUrlEncodedContent(new Dictionary<string, string>()54   {55     {"ID","382accff-57b2-4d6e-ae84-a61e00a3e3b5"},56     {"Name","Name" },57     {"QZH","111"}58   });59   HttpResponseMessage response = client.GetAsync(resource).Result;60   response = client.PostAsync(resource, content).Result;61   if (response.IsSuccessStatusCode)62   {63     bol = true;64     var result = response.Content.ReadAsStringAsync().Result;65   }66   return bol;67 }68 69 }
View Code

      例2:基于mvc+dotnet core WebApi,通過(guò)前端ajax來(lái)調(diào)用,下面直接貼幾段不同調(diào)用類型的代碼(由于Put 請(qǐng)求與Post請(qǐng)求類似就不再舉例貼代碼):

    片段1:基礎(chǔ)類型作為參數(shù)

 1  前端ajax代碼: 2 $.ajax({ 3 type: "get", 4 url: "http://localhost:27221/api/Charging/GetAllChargingData", 5 data: { id: 1, name: "Jim", bir: "1988-09-11"}, 6 success: function (data, status) { 7 if (status == "success") { 8 $("#div_test").html(data); 9 }10 }11 });12 Controller層代碼:13 [HttpGet]14 public string GetAllChargingData(interestingid,string name, DateTime bir)15 {return "ChargingData" + id;}
View Code

    片段2:實(shí)體類型作為參數(shù)

 1 前端ajax代碼:  2  $.ajax({ 3 type: "get", 4 url: "http://localhost:27221/api/Charging/GetByModel", 5 contentType: "application/json", 6 data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) }, 7 success: function (data, status) { 8 if (status == "success") { 9 $("#div_test").html(data);10 }11 }12 });13 Controller層代碼一(先序列化,再在后臺(tái)反序列的方式):14 [HttpGet]15 public string GetByModel(string strQuery)16 {17 TB_CHARGING oData=Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery));18 return "Charging" + oData.ID;19 }20 Controller層代碼二(在參數(shù)里面加上[FromUri]):21 [HttpGet]22 [HttpGet]23 public string GetAllChargingData([FromUri]TB_CHARGING obj)24 {25 return "ChargingData" + obj.ID;26 }
View Code

    片段3:?jiǎn)蝹€(gè)實(shí)體作為參數(shù):(post請(qǐng)求默認(rèn)是將表單里面的數(shù)據(jù)的key/value形式發(fā)送到服務(wù),而我們的服務(wù)器只需要有對(duì)應(yīng)的key/value屬性值的對(duì)象就可以接收到。而如果使用application/json,則表示將前端的數(shù)據(jù)以序列化過(guò)的json傳遞到后端,后端要把它變成實(shí)體對(duì)象,還需要反序列化的過(guò)程)

 1 方法一: (使用post請(qǐng)求的默認(rèn)參數(shù)類型,前端直接傳遞json類型的對(duì)象) 2 前端ajax代碼: 3 $.ajax({ 4 type: "post", 5 url: "http://localhost:27221/api/Charging/SaveData", 6 data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }, 7 success: function (data, status) {} 8 }); 9 方法二:(指定了contentType為application/json,需序列化待傳遞的對(duì)象)10 前端ajax代碼:11 var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };12 $.ajax({13 type: "post",14 url: "http://localhost:27221/api/Charging/SaveData",15 contentType: 'application/json',16 data: JSON.stringify(postdata),17 success: function (data, status) {}18 });19 Controller層代碼:20 [HttpPost]21 public bool SaveData(TB_CHARGING oData)22 {23 return true;24 }
View Code

    片段4:實(shí)體和基礎(chǔ)類型一起作為參數(shù)傳遞

 1 前端ajax代碼: 2 var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }; 3 $.ajax({ 4 type: "post", 5 url: "http://localhost:27221/api/Charging/SaveData", 6 contentType: 'application/json', 7 data: JSON.stringify({ NAME:"Lilei", Charging:postdata }), 8 success: function (data, status) {} 9 });10 Controller層代碼:11 [HttpPost]12 public object SaveData(dynamic obj)13 {14 var strName = Convert.ToString(obj.NAME);15 var oCharging = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(Convert.ToString(obj.Charging));16 return strName;17 }
View Code

    片段5:基礎(chǔ)類型數(shù)組作為參數(shù)傳遞

 1 前端ajax代碼: 2     var arr = ["1", "2", "3", "4"]; 3     $.ajax({ 4         type: "post", 5         url: "http://localhost:27221/api/Charging/SaveData", 6         contentType: 'application/json', 7         data: JSON.stringify(arr), 8         success: function (data, status) { } 9     });10 Controller層代碼:11         [HttpPost]12         public bool SaveData(string[] ids)13         {14             return true;15         }
View Code

    片段6:簡(jiǎn)單貼個(gè)Delete請(qǐng)求

 1     var arr = [ 2         { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }, 3         { ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" }, 4         { ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" } 5     ]; 6     $.ajax({ 7         type: "delete", 8         url: "http://localhost:27221/api/Charging/OptDelete", 9         contentType: 'application/json',10         data: JSON.stringify(arr),11         success: function (data, status) {}12     });13 Controller層:14         [HttpDelete]15         public bool OptDelete(List<TB_CHARGING> lstChargin)16         {17             return true;18         }
View Code

  總結(jié):記錄下個(gè)人的學(xué)習(xí)Asp.netCore RESTful WebApi的過(guò)程,不對(duì)之處歡迎指正。另:對(duì)于Controller層WebApi返回值的梳理建議參考官網(wǎng)文檔

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多