博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
20、ASP.NET MVC入门到精通——WebAPI
阅读量:6451 次
发布时间:2019-06-23

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

本系列目录:

微软有了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 IEnumerable
GetAllProducts() { 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

    View Code

    运行结果如下:

    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'");        }    }}
    View Code

    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; } }}
    View Code

    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; } }}
    View Code

    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 BaseEntity
    where 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 IList
    GetAll() { 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 List
    GetAllBySource() { 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 }}
    View Code

    4、调用代码:

    List
    list = DBHelper.Entitys.EProducts.GetAllBySource();

    在调用WebAPI之前,记得先运行WebAPI站点。

    当我们的WebAPI站点开发完成之后,我们可以使用Nuget安装一个插件自动生成API文档,这个插件同时还支持WebAPI在线测试的。

    转载地址:http://ycgwo.baihongyu.com/

    你可能感兴趣的文章
    操作系统os常识
    查看>>
    乱码的情况
    查看>>
    虚拟机centos 同一个tomcat、不同端口访问不同的项目
    查看>>
    DHCP的工作原理
    查看>>
    在不花一分钱的情况下,如何验证你的创业想法是否可行?《转》
    查看>>
    Linux/Android 性能优化工具 perf
    查看>>
    learn go recursive
    查看>>
    对于double小数点后取两位
    查看>>
    HashMap的小试牛刀
    查看>>
    GitHub使用教程、注册与安装
    查看>>
    论以结果为导向
    查看>>
    蓝桥杯模拟五 蒜头君下棋
    查看>>
    CODE[VS] 1294 全排列
    查看>>
    <<The C Programming Language>>讀書筆記
    查看>>
    Lodop属性和方法详解
    查看>>
    (转)CSS的display属性
    查看>>
    如何在目录中查找具有指定字符串的文件(shell)
    查看>>
    安卓学习笔记2
    查看>>
    angularJs按需加载代码(未验证)
    查看>>
    选择排序
    查看>>