c# Winfom客户端 GET 访问WebApi 方法

2021-03-12 11:27

阅读:437

标签:访问   turn   style   UNC   too   rtt   header   app   func   

服务方法

 1 [HttpGet]
 2 public string GetWebName(string name,string pwd)
 3 {
 4 Dictionarystring, string> dict = new Dictionarystring, 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);

                }

            });
        }

 

c# Winfom客户端 GET 访问WebApi 方法

标签:访问   turn   style   UNC   too   rtt   header   app   func   

原文地址:https://www.cnblogs.com/lzsin/p/12601912.html


评论


亲,登录后才可以留言!