前段时间学习WebApi的创建与调用,网上的信息千奇百怪(知识有限,看不懂啊),通过查阅资料及借鉴博友实例分析后总结一下,总结一套简单完整的WebApi创建及实例
首先创建一个WebApi服务(流程就不写了,网上的介绍多的像牛虱一样),但是该配置的要配置好哦
1.服务端
首先创建一个Control类,我这里命名为UserInfoController,逻辑代码可以在里面放飞吧。
下面举例说明
我们自定义一个路由方法(url: "{controller}/{action}/{id}"这个定义了我们url的规则,{controller}/{action}定义了路由的必须参数,{id}是可选参数)
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
这里我在WebApi方法里创建了两种Method (POST ,GET)
public class UserInfoController : ApiController
{ /// <summary>
/// //如果是GET方式时,调用的接口就是 http://localhost:61668/ActionApi/UserInfo/GetString
/// </summary>
/// <returns></returns>
[HttpPost]
public string GetString([FromBody]student info)
{
return "Name:" + info.name +"year:"+info.year;
} [HttpGet]
/// <summary>
/// 如果是GET方式时,调用的接口就是 http://localhost:61668/ActionApi/UserInfo/User?UserName=张三
/// </summary>
/// <param name="UserName"></param>
/// <returns></returns>
//[HttpPost] public List<string> User(string UserName)
{
List<string> s = new List<string>();
s.Add(UserName + "");
s.Add(UserName + "");
s.Add(UserName + "");
return s; }
}
2.客户端调用
2.1 WebRequest方式调用
public static string WebRequest_post(string url, string body)
{
//定义request并设置request的路径
WebRequest request = WebRequest.Create(url);
request.Method = "post";
//初始化request参数
//设置参数的编码格式,解决中文乱码
byte[] byteArray = Encoding.UTF8.GetBytes(body);
//设置request的MIME类型及内容长度
request.ContentType = "application/json; charset=UTF-8";
request.ContentLength = byteArray.Length;
//打开request字符流
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, , byteArray.Length);
dataStream.Close();
//定义response为前面的request响应
WebResponse response = request.GetResponse();
//定义response字符流
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
return reader.ReadToEnd();//读取所有
} public static string WebRequest_Get(string UNIT_NO)
{ Encoding encoding = Encoding.UTF8;
string url = "http://localhost:61668/ActionApi/UserInfo/User?UserName={0}";
url = string.Format(url, UNIT_NO);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
2.2 Htpclient
public static async void httpclient_post()
{
string url = "http://localhost:61668/ActionApi/UserInfo/GetString/";
//设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{ {"name",""},
{"year",""}, });
//await异步等待回应
var response = await http.PostAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
string s= await response.Content.ReadAsStringAsync(); }
} public static async void httpclient_Get(string url,string UNIT_NO)
{
url = string.Format(url, UNIT_NO);
//设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
//await异步等待回应
var response = await http.GetAsync(url);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
string s = await response.Content.ReadAsStringAsync();
}
}
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();
这几种方式亲测可用