博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET Web API 实例
阅读量:6643 次
发布时间:2019-06-25

本文共 11080 字,大约阅读时间需要 36 分钟。

 

创建Web API解决方案,命名为VCoinWebApi,并且创建了同名的Project,然后,创建一个Empty Project:Models,创建一个WPF Application Project:VCoinWebTester

 

在Models项目下,添加User类。User类的代码如下:

namespace Models{    public class User    {        public long ID { get; set; }        public string UserName { get; set; }        public Platform Platform { get; set; }        public string Status { get; set; }    }    public enum Platform    {        Facebook,        Youtube    }}

在VCoinWebApi项目下的Controllers文件夹上右键添加Web API 2 Controller - Empty。新建的UsersController代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;using Models;using Newtonsoft.Json.Linq;namespace VCoinWebApi.Controllers{    public class UsersController : ApiController    {        List
users = new List
{ new User { ID = 1, UserName = "Soup1", Platform = Platform.Facebook, Status = "User" }, new User { ID = 2, UserName = "Soup2", Platform = Platform.Facebook, Status = "User" }, new User { ID = 3, UserName = "Soup3", Platform = Platform.Facebook, Status = "User" }, new User { ID = 4, UserName = "Soup4", Platform = Platform.Facebook, Status = "User" }, }; public IEnumerable
GetAllUsers() { return users; } public User GetUserById(short id) { var user = users.FirstOrDefault((p) => p.ID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } else { return user; } } [HttpGet] [ActionName("GetUser")] public IEnumerable
GetUsersByName(string userName) { return users.Where( (p) => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase)); } [HttpPost] [ActionName("AddUser")] public User Add([FromBody]long id, string userName,int platform,string status) { User user = new User { ID = id, UserName = userName, Platform = (Platform)platform, Status = status }; if (user == null) { throw new HttpRequestException(); } users.Add(user); return user; } [HttpPost] [ActionName("AddUser")] public User AddUser([FromBody]User user) { if (user == null) { throw new HttpRequestException(); } users.Add(user); return user; } [HttpPost] public User Delete([FromBody]int id) { var user = users.FirstOrDefault((p) => p.ID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } else { users.Remove(user); return user; } } [HttpPost] [ActionName("Update")] public HttpResponseMessage UpdateUser([FromUri]int id,[FromBody]User user)//{"ID":1,"UserName":"Hello","Platform":1,"Status":"User"} { return Request.CreateResponse(HttpStatusCode.OK, user); } //[HttpPost] //[ActionName("Update")] //public HttpResponseMessage UpdateUser(JObject jo)//{"ID":1,"UserName":"Hello","Platform":1,"Status":"User"} //{ // User user = new User(); // user.ID = 1; // user.Platform = Platform.Youtube; // user.Status = "User"; // user.UserName = "Hello"; // return Request.CreateResponse(HttpStatusCode.OK, user); //} //[HttpPost] //[ActionName("Update")] //public void UpdateUser(JObject jo)//不返回值 //{ //} //[HttpPost] //[ActionName("Update")] //public bool UpdateUser(JObject jo)//返回:true //{ // return true; //} }}

修改App_Start文件夹下的WebApiConfig.cs文件的默认的路由规则,如下:

public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{action}/{id}",                defaults: new { id = RouteParameter.Optional }            );            config.EnableSystemDiagnosticsTracing();        }    }

在VCoinWebTester项目下添加WebApiRequest.cs类,类的主要的两个方法如下:

     ///         /// Post data to server        ///         ///         ///         /// in millionseconds        /// 
public static string PostRequest(string postData, string builderPath, int timeout) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] data = encoding.GetBytes(postData); UriBuilder builder = CreateUriBuilder(); builder.Path = builderPath; Uri requestUri = builder.Uri; // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUri); ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; myRequest.Method = "POST"; //myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentType = "application/json; charset=utf-8"; myRequest.ContentLength = data.Length; myRequest.CookieContainer = Cookie; myRequest.Timeout = timeout; string content = string.Empty; try { using (Stream newStream = myRequest.GetRequestStream()) { newStream.Write(data, 0, data.Length);// Send the data. } using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); content = reader.ReadToEnd();// Get response } } catch (WebException webEx) { System.Diagnostics.Debug.WriteLine(webEx.ToString()); //throw; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); //throw; } return content; }     public static string GetRequest(string path, string query) { UriBuilder builder = CreateUriBuilder(); builder.Path = path; builder.Query = query; Uri requestUri = builder.Uri; HttpWebRequest request = null; HttpWebResponse response = null; string ret = string.Empty; try { request = (HttpWebRequest)WebRequest.Create(requestUri); ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; request.CookieContainer = Cookie; response = request.GetResponse() as HttpWebResponse; using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { ret = reader.ReadToEnd(); } } } catch (WebException webEx) { ret = webEx.Message; //throw; } catch (Exception ex) { ret = ex.Message; //throw; } finally { if (response != null) { response.Close(); } } return ret; }

做完这些。就可以在MainWindow里面愉快地调用WebAPI了。

private void Button_AddUser_Click(object sender, RoutedEventArgs e)        {            User user = new User();            user.ID = 4;            user.Platform = Platform.Youtube;            user.Status = "User";            user.UserName = "Hello";            //      myRequest.ContentType = @"application/json; charset=utf-8";//可以发送json字符串作为参数            //      在Web API端,对应的方法是 AddUser([FromBody]User user)            //      客户端发送一个对象的Json序列化字符串,在API端可以自动反序列化为具体对象            string userJsonString = JsonConvert.SerializeObject(user);            //      myRequest.ContentType = "application/x-www-form-urlencoded";//只能发送&&&&&            //      在Web API端,对应的方法是Add([FromBody]long id, string userName,int platform,string status)            StringBuilder sb = new StringBuilder();            sb.Append(string.Format("id={0}", user.ID));            sb.Append(string.Format("&platform={0}", 0));            sb.Append(string.Format("&status={0}", user.Status));            sb.Append(string.Format("&userName={0}", user.UserName));            //      在API端的Add方法里面已经用ActionName注解属性强制指明了动作名称为AddUser            string path = "api/users/AddUser";            //      myRequest.ContentType = @"application/json; charset=utf-8";//可以发送json字符串作为参数            //      myRequest.ContentType = "application/x-www-form-urlencoded";//只能发送&&&&&            //      在WebApiRequest里面因为以及设置了前者,所以这里就发送Json字符串            string responseString = WebApiRequest.PostRequest(userJsonString, path);            WriteResult("添加User", responseString);        }
private void Button_UpdateUser_Click(object sender, RoutedEventArgs e)        {            //对应的方法是:UpdateUser([FromUri]int id,[FromBody]User user)            //1,是方法里面从Uri读取的参数            //user是序列化的Json字符串,需要从body读取            string path = "api/users/Update/1";            User user = new User();            user.ID = 1;            user.Platform = Platform.Youtube;            user.Status = "User";            user.UserName = "Hello";            string userJsonString = JsonConvert.SerializeObject(user);            string responseString = WebApiRequest.PostRequest(userJsonString, path);            WriteResult("更新User", responseString);        }
 

 

private void Button_GetAllUser_Click(object sender, RoutedEventArgs e)        {            string path = "api/users/GetAllUsers";            string responseString = WebApiRequest.GetRequest(path);            WriteResult("所有的User", responseString);        }        private void Button_GetProductByID_Click(object sender, RoutedEventArgs e)        {            int id = 0;            int.TryParse(TB_UserID.Text, out id);            string path = string.Format("api/users/GetUserById/{0}", id);            string responseString = WebApiRequest.GetRequest(path);            WriteResult("对应ID的User", responseString);        }
private void Button_GetUserByName_Click(object sender, RoutedEventArgs e)        {            string path = "api/users/GetUser";            string query = string.Format("userName={0}", TB_UserName.Text);            string responseString = WebApiRequest.GetRequest(path,query);            WriteResult("对应名字的User", responseString);        }

 

 

转载于:https://www.cnblogs.com/AlvinLiang/p/3808354.html

你可能感兴趣的文章
润乾报表 设置下拉日历的时间
查看>>
TCP与UDP的区别
查看>>
Weighted Effect Coding: Dummy coding when size matters
查看>>
Day15 - Python基础15 模块学习-selectors
查看>>
Nginx介绍及其环境搭建
查看>>
会话管理
查看>>
PHP7安装mysql扩展
查看>>
jQuery 隐藏/显示
查看>>
001 Math对象,数组和表的高级运用 字符串
查看>>
那些年一起用过的iOS开发利器之CocoaPods
查看>>
【转】Ubuntu11.10下安装Hadoop1.0.0(单机伪分布式)
查看>>
tcp_nodelay的作用
查看>>
echars 图表提示框自定义显示
查看>>
HLG 1543 序列难题[后缀数组]
查看>>
渲染流水线
查看>>
揭示同步块索引(中):如何获得对象的HashCode
查看>>
Python线程池及其原理和使用(超级详细)
查看>>
刷存在感-01
查看>>
在Linux里安装Samba(文件共享)方便在Windows下面操作
查看>>
PHP的两个科学计数法转换为字符串的方法
查看>>