一个非常轻量级的 Web API Demo

Posted s0611163

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个非常轻量级的 Web API Demo相关的知识,希望对你有一定的参考价值。

一个非常轻量级的 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测试:

技术图片

 

以上是关于一个非常轻量级的 Web API Demo的主要内容,如果未能解决你的问题,请参考以下文章

十条jQuery代码片段助力Web开发效率提升

[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作

线程-使用SimaphoreSlim类

使用轻量级JAVA 爬虫Gecco工具抓取新闻DEMO

从 url 中提取音频片段并使用纯 Web Audio API 播放

几条jQuery代码片段助力Web开发效率提升