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 = , UserName = "Soup1", Platform = Platform.Facebook, Status = "User" },
new User { ID = , UserName = "Soup2", Platform = Platform.Facebook, Status = "User" },
new User { ID = , UserName = "Soup3", Platform = Platform.Facebook, Status = "User" },
new User { ID = , 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 = 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, , 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 = ;
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}", ));
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 = ;
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 = ;
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);
}
ASP.NET Web API 实例的更多相关文章
- ASP.NET Web API自身对CORS的支持:从实例开始
在<通过扩展让ASP.NET Web API支持W3C的CORS规范>中我们通过自定义的HttpMessageHandler为ASP.NET Web API赋予了跨域资源共享的能力,具体来 ...
- 关于操作 ASP.NET Web API的实例
WCF的野心造成了它的庞大复杂,HTTP的单纯造就了它的简单优美.为了实现分布式Web应用,我们不得不将两者凑合在一起 —— WCF服务以HTTP绑定宿主于IIS. 于是有了让人晕头转向的配置.让人郁 ...
- ASP.NET Web API 框架研究 Controller实例的销毁
我们知道项目中创建的Controller,如ProductController都继承自ApiController抽象类,其又实现了接口IDisposable,所以,框架中自动调用Dispose方法来释 ...
- ASP.NET Web API实践系列02,在MVC4下的一个实例, 包含EF Code First,依赖注入, Bootstrap等
本篇体验在MVC4下,实现一个对Book信息的管理,包括增删查等,用到了EF Code First, 使用Unity进行依赖注入,前端使用Bootstrap美化.先上最终效果: →创建一个MVC4项目 ...
- 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用
由于ASP.NET Web API具有与ASP.NET MVC类似的编程方式,再加上目前市面上专门介绍ASP.NET Web API 的书籍少之又少(我们看到的相关内容往往是某本介绍ASP.NET M ...
- ASP.NET Web API Model-ActionBinding
ASP.NET Web API Model-ActionBinding 前言 前面的几个篇幅把Model部分的知识点划分成一个个的模块来讲解,而在控制器执行过程中分为好多个过程,对于控制器执行过程(一 ...
- ASP.NET Web API Model-ParameterBinding
ASP.NET Web API Model-ParameterBinding 前言 通过上个篇幅的学习了解Model绑定的基础知识,然而在ASP.NET Web API中Model绑定功能模块并不是被 ...
- ASP.NET Web API Model-ModelBinder
ASP.NET Web API Model-ModelBinder 前言 本篇中会为大家介绍在ASP.NET Web API中ModelBinder的绑定原理以及涉及到的一些对象模型,还有简单的Mod ...
- ASP.NET Web API Model-ValueProvider
ASP.NET Web API Model-ValueProvider 前言 前面一篇讲解了Model元数据,Model元数据是在Model绑定中很重要的一部分,只是Model绑定中涉及的知识点比较多 ...
随机推荐
- gulp.spritesmith修改px为rem单位
移动端开发中,使用gulp.spritesmith进行小图sprite并生成样式,但由于spritesmith默认是以px为单位,所以就把插件的内容修改了下让生成rem单位并且能把background ...
- JS常用的设计模式(11)—— 中介者模式
中介者对象可以让各个对象之间不需要显示的相互引用,从而使其耦合松散,而且可以独立的改变它们之间的交互. 打个比方,军火买卖双方为了安全起见,找了一个信任的中介来进行交易.买家A把钱交给中介B,然后从中 ...
- 关于hbase的read操作的深入研究 region到storefile过程
这里面说的read既包括get,也包括scan,实际底层来看这两个操作也是一样的.我们将要讨论的是,当我们从一张表读取数据的时候hbase到底是怎么处理的.分二种情况来看,第一种就是表刚创建,所有pu ...
- systemctl
旧指令 新指令 使某服务自动启动 chkconfig --level 3 httpd on systemctl enable httpd.service 使某服务不自动启动 chkconfig - ...
- 著名的二分查找的BUG
int binarySearch(int a[], int key, int length) { int low = 0; int high = length - 1; while (low < ...
- C puzzles详解【46-50题】
第四十六题 What does the following macro do? #define ROUNDUP(x,n) ((x+n-1)&(~(n-1))) 题目讲解: 参考:http:// ...
- VHDL学习札记:library and Package
参考:http://www.cnblogs.com/garylee/archive/2012/11/16/2773596.htmlhttp:// http://forums.xilinx.com ...
- jQuery判断元素离页面顶部的高度
<script language="javascript" type="text/javascript"> jQuery(document).rea ...
- C#局域网桌面共享软件制作(二)
链接C#局域网桌面共享软件制作(一) 如果你运行这个软件查看流量监控就会发现1~2M/s左右的上传下载,并且有时会报错“参数无效”,如果你将屏幕截图保存到本地的话每张图片大概4M(bmp).120KB ...
- MongoDB 相关下载
MongoDB 下载:http://www.mongodb.org/ 本实例中MongoDB的C#驱动,支持linq:https://github.com/samus/mongodb-csharp M ...