C# webapi简单学习
转自:https://www.cnblogs.com/zyg316/p/10491242.html
创建WebApi项目:
在VS工具中创建一个ASP.NET Web应用程序
选择Webapi
一个webapi项目就创建好了
这里简单的写一个post和get两种请求的方法,由于post请求参数需要参数体的形式,一般用json作为参数,这里简单创建一个实体类,放上参数,我这里就放一个,可根据项目自己设置相应的参数
注意的是,post请求的时候,json里的键值对 键的名字要和实体中的一样,过来实体接收参数会自动将json值拆分到各个对应的名字上
然后先写post方法,记得要写请求方式[HttpPost],注意这个参数的写法
[HttpPost] public string demo([FromBody]Contact name) { string nn = name.Name; string result = string.Empty; result = "您的参数是:" + nn; return result; }
Get方法可以直接获取参数,注意[HttpGet]
[HttpGet] public string wxs(string name) { string result = string.Empty; result = "{Name:\"" + name + "\"}"; return result; }
一个简单的webapi就写完了,现在试试请求这个webapi,我这里用C#控制台应用程序写一个简单的调用
为了方便测试,我直接将这个webapi发布到了本机的IIS上
Post请求:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string ss = HttpPost("http://localhost:8097/api/Contact/demo", "{\"Name\":\"zhangsan\"}"); Console.WriteLine(ss); Console.ReadLine(); } public static string HttpPost(string url, string body) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } } }
Get请求:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string ss = HttpGet("http://localhost:8097/api/Contact/wxs?name=zhangsan"); Console.WriteLine(ss); Console.ReadLine(); } public static string HttpGet(string url) { Encoding encoding = Encoding.UTF8; 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(); } } } }
本博有部分内容来自网络,如有问题请联系:hebeilijianghua@qq.com,并注明来自博客园。