首页 > 代码库 > ASP.NET Web API 实例
ASP.NET Web API 实例
ASP.NET Web API 入门大杂烩
创建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<User> users = new List<User> { 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<User> 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<User> 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类,类的主要的两个方法如下:
/// <summary> /// Post data to server /// </summary> /// <param name="postData"></param> /// <param name="builderPath"></param> /// <param name="timeout">in millionseconds</param> /// <returns></returns> public static string PostRequest(string postData, string builderPath, int timeout) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] data =http://www.mamicode.com/ 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); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。