本系列目录:
微软有了Webservice和WCF,为什么还要有WebAPI?
用过WCF的人应该都清楚,面对那一大堆复杂的配置文件,有时候一出问题,真的会叫人抓狂。而且供不同的客户端调用不是很方便。不得不承认WCF的功能确实非常强大,可是有时候我们通常不需要那么复杂的功能,只需要简单的仅通过使用Http或Https来调用的增删改查功能,这时,WebAPI应运而生。那么什么时候考虑使用WebAPI呢?
当你遇到以下这些情况的时候,就可以考虑使用Web API了。
- 需要Web Service但是不需要SOAP
- 需要在已有的WCF服务基础上建立non-soap-based http服务
- 只想发布一些简单的Http服务,不想使用相对复杂的WCF配置
- 发布的服务可能会被带宽受限的设备访问
- 希望使用开源框架,关键时候可以自己调试或者自定义一下框架
熟悉MVC的朋友你可能会觉得Web API 与MVC很类似。
Demo
1、新建项目,WebApi
2、新建类Product
public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } }
3、新建控制器Products,为了演示,我这里不连接数据库,直接代码中构造假数据
using System.Net.Http; using System.Web.Http; public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerableGetAllProducts() { return products; } public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } }
4、新建Index.html来测试WebAPI的调用,代码如下:
Product App All Products
Search by ID
运行结果如下:
WebAPI授权
1、新建授权过滤器类APIAuthorizeAttribute.cs
/* ============================================================================== * 功能描述:APIAuthorizeAttribute * 创 建 者:Zouqj * 创建日期:2015/11/3 11:37:45 ==============================================================================*/using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Security.Principal;using System.Text;using System.Threading;using System.Web;using System.Web.Http.Filters;using Uuch.HP.WebAPI.Helper;namespace Uuch.HP.WebAPI.Filter{ public class APIAuthorizeAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { //如果用户使用了forms authentication,就不必在做basic authentication了 if (Thread.CurrentPrincipal.Identity.IsAuthenticated) { return; } var authHeader = actionContext.Request.Headers.Authorization; if (authHeader != null) { if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && !String.IsNullOrWhiteSpace(authHeader.Parameter)) { var credArray = GetCredentials(authHeader); var userName = credArray[0]; var key = credArray[1]; string ip = System.Web.HttpContext.Current.Request.UserHostAddress; //if (IsResourceOwner(userName, actionContext)) //{ //You can use Websecurity or asp.net memebrship provider to login, for //for he sake of keeping example simple, we used out own login functionality if (APIAuthorizeInfoValidate.ValidateApi(userName,key,ip))//Uuch.HPKjy.Core.Customs.APIAuthorizeInfo.GetModel(userName, key, ip) != null { var currentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null); Thread.CurrentPrincipal = currentPrincipal; return; } //} } } HandleUnauthorizedRequest(actionContext); } private string[] GetCredentials(System.Net.Http.Headers.AuthenticationHeaderValue authHeader) { //Base 64 encoded string var rawCred = authHeader.Parameter; var encoding = Encoding.GetEncoding("iso-8859-1"); var cred = encoding.GetString(Convert.FromBase64String(rawCred)); var credArray = cred.Split(':'); return credArray; } private bool IsResourceOwner(string userName, System.Web.Http.Controllers.HttpActionContext actionContext) { var routeData = actionContext.Request.GetRouteData(); var resourceUserName = routeData.Values["userName"] as string; if (resourceUserName == userName) { return true; } return false; } private void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='eLearning' location='http://localhost:8323/APITest'"); } }}
2、添加验证方法类APIAuthorizeInfoValidate.cs
using Newtonsoft.Json;/* ============================================================================== * 功能描述:APIAuthorizeInfoValidate * 创 建 者:Zouqj * 创建日期:2015/11/3 16:26:10 ==============================================================================*/using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Uuch.HP.WebAPI.Helper{ public class APIAuthorizeInfo { public string UserName { get; set; } public string Key { get; set; } } public class APIAuthorizeInfoValidate { public static bool ValidateApi(string username, string key, string ip) { var _APIAuthorizeInfo = JsonConvert.DeserializeObject
>(WebConfigHelper.ApiAuthorize); var ips = WebConfigHelper.IPs.Contains(",") ? WebConfigHelper.IPs.Split(',') : new string[] { WebConfigHelper.IPs }; if (_APIAuthorizeInfo != null && _APIAuthorizeInfo.Count > 0) { foreach (var v in _APIAuthorizeInfo) { if (v.UserName == username && v.Key == key && ips.Contains(ip)) { return true; } } } return false; } }}
3、把添加到全局过滤器中,这里要注意了,不要添加到FilterConfig.cs,而要添加到WebApiConfig.cs,因为FilterConfig是MVC用的,我们这里是WebAPI。
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new APIAuthorizeAttribute()); } }
使用C#来调用WebAPI
以下用到的几个类,已经被我封装好了,可以直接使用。
1、新建webAPI站点,然后新建控制器RProducts
public class RProductsController : ApiController { ////// 备案商品回执记录回调接口 /// /// ///public int Put(List lst) { return ReceiptInfo.UpdateReceiptProductInfo(lst); } }
2、新建类WebApiClient.cs
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using DBHelper.Entitys;namespace DBHelper{ public static class WebApiClient{ static void SetBasicAuthorization(HttpClient client) { HttpRequestHeaders header=client.DefaultRequestHeaders; string user = ConfigHelper.UserName; string key = ConfigHelper.Key; Encoding encoding = Encoding.UTF8; // Add an Accept header for JSON format. // 为JSON格式添加一个Accept报头 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Base64编码 var data = Convert.ToBase64String(encoding.GetBytes(user + ":" + key)); //设置AuthenticationHeaderValue header.Authorization = new AuthenticationHeaderValue("Basic", data); //通过HttpRequestHeaders.Add //header.Add("Authorization", "Basic " + data); } public static List GetAll(string url) { List li = new List (); HttpClient client = new HttpClient(); SetBasicAuthorization(client); // List all products. // 列出所有产品 HttpResponseMessage response = client.GetAsync(url).Result;// Blocking call(阻塞调用)! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! // 解析响应体。阻塞! li = response.Content.ReadAsAsync
>().Result; } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } return li; } public static T GetByFilter(string url) { T entity = default(T); HttpClient client = new HttpClient(); SetBasicAuthorization(client); // List all products. // 列出所有产品 HttpResponseMessage response = client.GetAsync(url).Result;// Blocking call(阻塞调用)! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! // 解析响应体。阻塞! entity = response.Content.ReadAsAsync ().Result; } return entity; } public static T Get(string url,string id) { T entity=default(T); HttpClient client = new HttpClient(); SetBasicAuthorization(client); // List all products. // 列出所有产品 HttpResponseMessage response = client.GetAsync(string.Format("{0}/{1}",url,id)).Result;// Blocking call(阻塞调用)! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! // 解析响应体。阻塞! entity = response.Content.ReadAsAsync ().Result; } return entity; } public static bool Edit(string url,List value) { HttpClient client = new HttpClient(); SetBasicAuthorization(client); var response = client.PutAsJsonAsync(url,value).Result; if (response.IsSuccessStatusCode) { return true; } else { return false; } } public static bool Edit(string url, Dictionary dic) { HttpClient client = new HttpClient(); SetBasicAuthorization(client); var response = client.PutAsJsonAsync(url, dic).Result; if (response.IsSuccessStatusCode) { return true; } else { return false; } } public static bool EditModel(string url, List value) { HttpClient client = new HttpClient(); SetBasicAuthorization(client); var response = client.PutAsJsonAsync(url, value).Result; if (response.IsSuccessStatusCode) { return true; } else { return false; } } public static List GetList (string url, List value) { List list = new List (); HttpClient client = new HttpClient(); SetBasicAuthorization(client); var response = client.PostAsJsonAsync(url, value).Result; if (response.IsSuccessStatusCode) { list = response.Content.ReadAsAsync
>().Result; } else { list = new List (); } return list; } }}
3、新建类BaseEntity.cs
using NHibernate;using NHibernate.Criterion;using System;using System.Collections.Generic;using System.Configuration;using System.Data.Common;using System.Linq;using System.Text;namespace DBHelper{ public abstract class BaseEntitywhere T : BaseEntity { #region 属性 /// /// 编号 /// public string V_PreInvtId { get; set; } ////// 回执状态 /// public int V_OpResult { get; set; } ////// 操作时间 /// public DateTime D_optime { get; set; } ////// 备注 /// public string V_NoteS { get; set; } #endregion public virtual TID ID { get; set; } #region ////// Session配置文件路径 /// protected static readonly string SessionFactoryConfigPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NHibernate.config"); ////// 返回对应的Session. /// protected static ISession NHibernateSession { get { return NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath); } } #endregion #region common ////// 根据ID从数据库获取一个类型为T的实例 /// public static T GetById(TID id, bool shouldLock) { T entity; if (shouldLock) { entity = NHibernateSession.Get(id, LockMode.Upgrade); } else { entity = NHibernateSession.Get (id); } return entity; } /// /// 根据ID从数据库获取一个类型为T的实例 /// public static T GetById(TID id) { return GetById(id, false); } ////// 获取所有的类型为T的对象 /// public static IListGetAll() { return GetByCriteria(); } /// /// 根据给定的 public static IList来查询结果 /// 如果没有传入 , 效果与 一致. /// GetByCriteria(params ICriterion[] criterion) { ICriteria criteria = NHibernateSession.CreateCriteria(typeof(T)); foreach (ICriterion criterium in criterion) { criteria.Add(criterium); } criteria.AddOrder(new Order("ID", false)); return criteria.List (); } #endregion #region entity /// /// 根据exampleInstance的属性值来查找对象,返回与其值一样的对象对表。 /// exampleInstance中值为0或NULL的属性将不做为查找条件 /// /// 参考对象 /// 要排除的查询条件属性名 ///public virtual IList GetByExample(T exampleInstance, params string[] propertiesToExclude) { ICriteria criteria = NHibernateSession.CreateCriteria(exampleInstance.GetType()); Example example = Example.Create(exampleInstance); foreach (string propertyToExclude in propertiesToExclude) { example.ExcludeProperty(propertyToExclude); } example.ExcludeNone(); example.ExcludeNulls(); example.ExcludeZeroes(); criteria.Add(example); criteria.AddOrder(new Order("ID", false)); return criteria.List (); } /// /// 使用 ///来返回一个唯一的结果,如果结果不唯一会抛出异常 /// public virtual T GetUniqueByExample(T exampleInstance, params string[] propertiesToExclude) { IList foundList = GetByExample(exampleInstance, propertiesToExclude); if (foundList.Count > 1) { throw new NonUniqueResultException(foundList.Count); } if (foundList.Count > 0) { return foundList[0]; } else { return default(T); } } /// /// 将指定的对象保存到数据库,并立限提交,并返回更新后的ID /// See http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-id-assigned. /// //public virtual T Save() //{ // T entity = (T)this; // NHibernateSession.Save(entity); // NHibernateSession.Flush(); // return entity; //} ////// 将指定的对象保存或更新到数据库,并返回更新后的ID /// //public virtual T Merge() //{ // T entity = (T)this; // NHibernateSession.Merge(entity); // NHibernateSession.Flush(); // return entity; //} ///// ///// 从数据库中删除指定的对象 ///// //public virtual void Delete() //{ // T entity = (T)this; // NHibernateSession.Delete(entity); // NHibernateSession.Flush(); //} public virtual DbTransaction BeginTransaction() { ITransaction tran = NHibernateSession.BeginTransaction();// NHibernateSessionManager.Instance.BeginTransactionOn(SessionFactoryConfigPath); return new DbTransaction(tran); } ////// 提交所有的事务对象,并Flush到数据库 /// public virtual void CommitChanges() { if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath)) { NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigPath); } else { // 如果不是事务模式,就直接调用Flush来更新 NHibernateSession.Flush(); } } #endregion #region WebApi获取数据 public static string Url { get { string url = System.Configuration.ConfigurationManager.AppSettings[typeof(T).Name]; if (string.IsNullOrEmpty(url)) { throw new Exception(string.Format("“{0}”未包含URL配置", typeof(T).Name)); } return url; } } public static ListGetAllBySource() { return WebApiClient .GetAll(Url); } public static void EditBySource(List value) { WebApiClient .Edit(Url, value); } public static void EditBySource(Dictionary dic) { WebApiClient .Edit(Url, dic); } public static T GetOneBySource(string id) { return WebApiClient .Get(Url, id); } public static void EditBySourceByModel(List value) { WebApiClient .EditModel(Url, value); } #endregion } public class DbTransaction : IDisposable { ITransaction _transaction; public DbTransaction(ITransaction transaction) { _transaction = transaction; } #region IDisposable 成员 public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _transaction.Dispose(); _transaction = null; } } #endregion #region ITransaction 成员 public void Begin(System.Data.IsolationLevel isolationLevel) { _transaction.Begin(isolationLevel); } public void Begin() { _transaction.Begin(); } public void Commit() { _transaction.Commit(); } public void Enlist(System.Data.IDbCommand command) { _transaction.Enlist(command); } public bool IsActive { get { return _transaction.IsActive; } } public void RegisterSynchronization(NHibernate.Transaction.ISynchronization synchronization) { _transaction.RegisterSynchronization(synchronization); } public void Rollback() { _transaction.Rollback(); } public bool WasCommitted { get { return _transaction.WasCommitted; } } public bool WasRolledBack { get { return _transaction.WasRolledBack; } } #endregion }}
4、调用代码:
Listlist = DBHelper.Entitys.EProducts.GetAllBySource();
在调用WebAPI之前,记得先运行WebAPI站点。
当我们的WebAPI站点开发完成之后,我们可以使用Nuget安装一个插件自动生成API文档,这个插件同时还支持WebAPI在线测试的。