一個非常輕量級的 Web API Demo,代碼量很少,實現了方法攔截器,token校驗,異常攔截器,緩存 創建項目:如果選擇Web API,項目中東西會比較多,這裡選擇Empty,把下麵的Web API勾上,MVC不要勾 項目目錄結構: Global.asax.cs代碼:這裡配置方法攔截器和異常攔 ...
一個非常輕量級的 Web API Demo,代碼量很少,實現了方法攔截器,token校驗,異常攔截器,緩存
創建項目:如果選擇Web API,項目中東西會比較多,這裡選擇Empty,把下麵的Web API勾上,MVC不要勾
項目目錄結構:
Global.asax.cs代碼:這裡配置方法攔截器和異常攔截器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Routing; namespace WebApiDemo { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configuration.Filters.Add(new MyExceptionFilter()); GlobalConfiguration.Configuration.Filters.Add(new MyActionFilter()); GlobalConfiguration.Configure(WebApiConfig.Register); } } }View Code
MyActionFilter攔截器代碼:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace WebApiDemo { public class MyActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { object value; if (actionContext.ActionArguments.TryGetValue("token", out value)) { if (value.ToString() != "000") { var errMsg = new { errorMsg = "token不匹配" }; string str = JsonConvert.SerializeObject(errMsg); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.UTF8, "application/json") }; actionContext.Response = result; } } base.OnActionExecuting(actionContext); } } }View Code
MyExceptionFilter攔截器代碼:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http.Filters; namespace WebApiDemo { public class MyExceptionFilter : ExceptionFilterAttribute { //重寫基類的異常處理方法 public override void OnException(HttpActionExecutedContext actionExecutedContext) { var errMsg = new { errorMsg = "攔截到異常:" + actionExecutedContext.Exception.Message }; string str = JsonConvert.SerializeObject(errMsg); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.UTF8, "application/json") }; actionExecutedContext.Response = result; base.OnException(actionExecutedContext); } } }View Code
一個簡單的緩存工具類:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching; namespace WebApiDemo { public class CacheHelper { #region 獲取並緩存數據 /// <summary> /// 獲取並緩存數據 /// </summary> /// <param name="cacheKey">鍵</param> /// <param name="func">在此方法中初始化數據</param> /// <param name="expirationSeconds">緩存過期時間</param> public static T GetValue<T>(string cacheKey, Func<T> func, int expirationSeconds = 0) { object cacheValue = HttpRuntime.Cache.Get(cacheKey); if (cacheValue != null) { return (T)cacheValue; } else { T value = func(); HttpRuntime.Cache.Insert(cacheKey, value, null, DateTime.Now.AddSeconds(expirationSeconds), Cache.NoSlidingExpiration); return value; } } #endregion } }View Code
控制器MyApiController.cs代碼:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using WebApiDemo.Models; namespace WebApiDemo.Controllers { [RoutePrefix("api/MyApi")] public class MyApiController : ApiController { [HttpGet] [Route("GetAction")] public HttpResponseMessage GetAction(string token, string param) { var obj = new { param = param }; return ToJson(obj); } [HttpPost] [Route("PostAction")] public HttpResponseMessage PostAction(string token, string param, [FromBody] MyData data) { Random rnd = new Random(); int d = CacheHelper.GetValue<int>("MyCacheKey1", () => { return rnd.Next(1, 10000); }, 20); var obj = new { param = param, data = data, cache = d.ToString() }; return ToJson(obj); } [HttpGet] [Route("ErrorAction")] public HttpResponseMessage ErrorAction(string token, string param) { var obj = new { param = param }; int a = Convert.ToInt32("abc"); return ToJson(obj); } private HttpResponseMessage ToJson(object obj) { string str = JsonConvert.SerializeObject(obj); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.UTF8, "application/json") }; return result; } } }View Code
發佈:
部署在IIS,用Postman測試: