服务方法
1 [HttpGet] 2 public string GetWebName(string name,string pwd) 3 { 4 Dictionary<string, string> dict = new Dictionary<string, string>(); 5 dict.Add("姓名", Convert.ToString(name)); 6 dict.Add("密码", Convert.ToString(pwd)); 7 8 return Tools.ConvertToJsonStr(dict); 9 10 }
客户端调用
1 string Para = "name=0068&pwd=111111"; 2 string url = "http://localhost:10450/api/EmpInfo/GetWebName?"+ Para; 3 textBox2.Text = HttpGet(url);
1 string HttpGet(string URL) 2 { 3 // 创建HttpWebRequest对象 4 HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(URL); 5 httpRequest.Method = "GET"; 6 httpRequest.Headers.Add("Authorization", "lzsin"); 7 8 9 try 10 { 11 using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse()) 12 { 13 StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); 14 string responseString = sr.ReadToEnd(); 15 return responseString; 16 } 17 } 18 catch (WebException ex) 19 { 20 var res = (HttpWebResponse)ex.Response; 21 StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); 22 string str = sr.ReadToEnd(); 23 return str; 24 } 25 }
JQuery访问
$.ajax({ type: "get", dataType: ‘json‘,//服务器返回json格式数据 contentType: ‘application/json‘,//如果是针对[FromBody]string 参数 contentType 需要注释掉,不然会接收不到值 url: "http://localhost:10450/api/EmpInfo/GetWebName", data: { name: "用户名", pwd: "用户密码" } , headers: { Authorization: "lzsin" }, success: function (data, response, status) { alert(data); }, error: function (data) { console.log(data); alert(‘失败!‘ + data["responseText"], data, ‘warning‘); } }); }