WebApi調用通用方法

WebApi傳遞基礎參數的時候可能會有各類各樣的問題,有的須要在服務端增長[FromBody]的特性,有的須要增長一層封裝爲實體,有的用動態類型,下面介紹一個方便的調用方法。經過WebClient類。代碼以下,須要什麼參數只須要在QueryString中添加便可。json

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);
            }
        }
相關文章
相關標籤/搜索