webapi filter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace ApiFilter
{
    public class ApiAuthorFilter: AuthorizeAttribute
    {
        public ApiAuthorFilter(Func<string, Dictionary<string, string>> func) {
            this.Func = func;
        }
        private readonly Func<string, Dictionary<string, string>> Func;
        //private QD_Base_SubjectIBLL qD_Base_SubjectIBLL = new QD_Base_SubjectBLL();
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="actionContext"></param>
        private string ExceptionMessage;
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //如果用户方位的Action带有AllowAnonymousAttribute,则不进行授权验证
            if (((ReflectedHttpActionDescriptor)actionContext.ActionDescriptor).MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), true)
|| actionContext.ActionDescriptor.ControllerDescriptor.ControllerType.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }
            //var str = actionContext.Request.Headers.Authorization;
            IEnumerable<string> xkey;
            if (actionContext.Request.Headers.TryGetValues("X-key", out xkey)&&xkey.Count() > 0)
            {
                var value = xkey.First();
                var entity = Func(value);
                if (entity!=null&&entity.Count>0)
                {
                    foreach(var i in entity)
                    {
                        actionContext.Request.Headers.Add(i.Key,i.Value);
                    }
                }
                else
                {
                    ExceptionMessage = "Token 有错";
                    actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError(ExceptionMessage));
                }
            }
            else
            {
                ExceptionMessage = "Token 为空";
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError(ExceptionMessage));
            }
        }
    }


        ///失败的时候的操作
        //protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        //{
        //    var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
        //    response.Headers.Add("Location", "http://www.google.com");
        //    actionContext.Response = response;
        //}
    
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using ApiFilter.LogHelper;
using Newtonsoft.Json;
namespace ApiFilter
{
    public class OrginActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            try
            {
                string str;
                string absolute = actionContext.Request.RequestUri.AbsolutePath;
                string Method = actionContext.Request.Method.Method.ToUpper();
                if (Method == "GET")
                {
                    str = actionContext.Request.RequestUri.Query;
                }
                else
                {
                    str = JsonConvert.SerializeObject(actionContext.ActionArguments);
                }
                Task.Factory.StartNew(() => Log.Instance.info($"控制器:{absolute},传的方式:{Method},值:{str}"));
            }
            catch (Exception ex)
            {
                Task.Factory.StartNew(() => Log.Instance.Error(ex.StackTrace.ToString()));
            }
            finally { 
                base.OnActionExecuting(actionContext);
            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            try
            {
                if (actionExecutedContext.Exception == null)
                {
                    var oldObjectContent = (actionExecutedContext.ActionContext.Response.Content as ObjectContent);
                    var data = new { data = oldObjectContent.Value, msg = "1" };
                    var newContent = new ObjectContent<object>(data, oldObjectContent.Formatter);
                    actionExecutedContext.ActionContext.Response.Content = newContent;
                }
            }
            catch (Exception ex)
            {
                var logInfo = Log.Instance;
                logInfo.Error(ex.StackTrace);
            }
            finally {
                base.OnActionExecuted(actionExecutedContext);
            }
        }
    }
}
using ApiFilter.LogHelper;
using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;

namespace ApiFilter
{
    public class OrginExceptionFilter: ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            try
            {
                actionExecutedContext.ActionContext.Response = new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.InternalServerError };
                var data = new { data = actionExecutedContext.Exception.Message, msg = "3", info = actionExecutedContext.Exception.StackTrace.ToString() };
                var newContent = new ObjectContent<object>(data, new JsonMediaTypeFormatter());
                actionExecutedContext.ActionContext.Response.Content = newContent;
            }
            catch (Exception ex)
            {
                var logInfo = Log.Instance;
                logInfo.Error(ex.StackTrace);
            }
            finally
            {
                base.OnException(actionExecutedContext);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值