c# WebApi创建及客户端调用

前段时间学习WebApi的创建与调用,网上的信息千奇百怪(知识有限,看不懂啊),通过查阅资料及借鉴博友实例分析后总结一下,总结一套简单完整的WebApi创建及实例

首先创建一个WebApi服务(流程就不写了,网上的介绍多的像牛虱一样),但是该配置的要配置好哦

1.服务端

首先创建一个Control类,我这里命名为UserInfoController,逻辑代码可以在里面放飞吧。

下面举例说明

我们自定义一个路由方法(url: "{controller}/{action}/{id}"这个定义了我们url的规则,{controller}/{action}定义了路由的必须参数,{id}是可选参数

 1 public class RouteConfig
 2     {
 3         public static void RegisterRoutes(RouteCollection routes)
 4         {
 5             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 6 
 7             routes.MapRoute(
 8                 name: "",
 9                 url: "{controller}/{action}/{id}",
10                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
11             );
12         }
13     }
View Code

这里我在WebApi方法里创建了两种Method   (POST ,GET)

 1  public class UserInfoController : ApiController
 2     {
 3 
 4         /// <summary>
 5         /// //如果是GET方式时,调用的接口就是 http://localhost:61668/ActionApi/UserInfo/GetString
 6         /// </summary>
 7         /// <returns></returns>
 8         [HttpPost]
 9         public string GetString([FromBody]student info)
10         {
11             return "Name:" + info.name   +"year:"+info.year;
12         }
13 
14         [HttpGet]
15         /// <summary>
16         /// 如果是GET方式时,调用的接口就是 http://localhost:61668/ActionApi/UserInfo/User?UserName=张三
17         /// </summary>
18         /// <param name="UserName"></param>
19         /// <returns></returns>
20         //[HttpPost]
21 
22         public List<string> User(string UserName)
23         {
24             List<string> s = new List<string>();
25             s.Add(UserName + "1");
26             s.Add(UserName + "2");
27             s.Add(UserName + "3");
28             return s;
29 
30         }
31     }
View Code

2.客户端调用
2.1 WebRequest方式调用

 1   public static string WebRequest_post(string url, string body)
 2         {
 3             //定义request并设置request的路径
 4             WebRequest request = WebRequest.Create(url);
 5             request.Method = "post";
 6             //初始化request参数
 7             //设置参数的编码格式,解决中文乱码
 8             byte[] byteArray = Encoding.UTF8.GetBytes(body);
 9             //设置request的MIME类型及内容长度
10             request.ContentType = "application/json; charset=UTF-8";
11             request.ContentLength = byteArray.Length;
12             //打开request字符流
13             Stream dataStream = request.GetRequestStream();
14             dataStream.Write(byteArray, 0, byteArray.Length);
15             dataStream.Close();  
16             //定义response为前面的request响应
17             WebResponse response = request.GetResponse();
18             //定义response字符流
19             dataStream = response.GetResponseStream();
20             StreamReader reader = new StreamReader(dataStream);
21              return  reader.ReadToEnd();//读取所有
22         }
23      
24         public static string WebRequest_Get(string UNIT_NO)
25         {
26           
27             Encoding encoding = Encoding.UTF8;
28             string url = "http://localhost:61668/ActionApi/UserInfo/User?UserName={0}";
29             url = string.Format(url, UNIT_NO);
30             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
31             request.Method = "GET";
32             request.Accept = "text/html, application/xhtml+xml, */*";
33             request.ContentType = "application/json";
34             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
35             using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
36             {
37                 return reader.ReadToEnd();
38             }
39         }
View Code

2.2 Htpclient

 1  public  static async void  httpclient_post()
 2         {
 3             string url = "http://localhost:61668/ActionApi/UserInfo/GetString/";
 4             //设置HttpClientHandler的AutomaticDecompression
 5             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
 6             //创建HttpClient(注意传入HttpClientHandler)
 7             using (var http = new HttpClient(handler))
 8             {
 9                 //使用FormUrlEncodedContent做HttpContent
10                 var content = new FormUrlEncodedContent(new Dictionary<string, string>()
11                 {    {"name","6"},
12                      {"year","4"},
13                    
14                  });
15                 //await异步等待回应
16                 var response = await http.PostAsync(url, content);
17                 //确保HTTP成功状态值
18                 response.EnsureSuccessStatusCode();
19                 //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)         
20                 string s= await response.Content.ReadAsStringAsync();
21 
22             }
23         }
24 
25         public static async void httpclient_Get(string url,string UNIT_NO)
26         {
27             url = string.Format(url, UNIT_NO);
28             //设置HttpClientHandler的AutomaticDecompression
29             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
30             //创建HttpClient(注意传入HttpClientHandler)
31             using (var http = new HttpClient(handler))
32             {
33                 //使用FormUrlEncodedContent做HttpContent
34                 //await异步等待回应
35                 var response = await http.GetAsync(url);
36                 //确保HTTP成功状态值
37                 response.EnsureSuccessStatusCode();
38                 //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)         
39                 string s = await response.Content.ReadAsStringAsync();
40             }
41         }
View Code

3.函数调用

            MessageBox.Show(API.WebRequest_Get("张三"));
             MessageBox.Show(API.WebRequest_post("http://localhost:61668/ActionApi/UserInfo/GetString/", "{name:\"张三\",year:\"25\"}"));
            API.httpclient_post();

            API.httpclient_Get();
            这几种方式亲测可用

猜你喜欢

转载自www.cnblogs.com/TechnologyDictionary/p/10432513.html