码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2020-03-30 23:04:10      阅读:245      评论:0      收藏:0      [点我收藏+]

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

服务方法

 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);

                }

            });
        }

 

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!