您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)WebApi如何調(diào)用通用方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
WebApi傳遞基礎(chǔ)參數(shù)的時(shí)候可能會有各種各樣的問題,有的需要在服務(wù)端增加[FromBody]的特性,有的需要增加一層封裝為實(shí)體,有的用動態(tài)類型。通過WebClient類。代碼如下,需要什么參數(shù)只需要在QueryString中添加即可。
try { WebClient client = new WebClient(); //client.QueryString.Add("account", "馮寶寶"); //client.QueryString.Add("password", "7777"); client.QueryString.Add("name", "馮寶寶"); client.Encoding = Encoding.UTF8; client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); //string result = client.UploadString("http://localhost:51151/Api/Users/Login", ""); string result = client.UploadString("http://localhost:51151/Api/Users/WithStringParamNoFromBody", ""); } catch (Exception ex) { }
后端WebApi代碼如下:
[AllowAnonymous] [HttpPost] public IEnumerable<Users> WithStringParamNoFromBody(string name) { return _userList; } [AllowAnonymous] [HttpPost] public string Login(string account, string password) { if (account.Equals("馮寶寶") && password.Equals("7777")) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, account, DateTime.Now, DateTime.Now.AddMinutes(5), true, $"{account}&{password}", FormsAuthentication.FormsCookiePath); var result = new { Result = true, Ticket = FormsAuthentication.Encrypt(ticket) }; return JsonConvert.SerializeObject(result); } else { var result = new { Result = false }; return JsonConvert.SerializeObject(result); } }
關(guān)于“WebApi如何調(diào)用通用方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。