webapiフィルター

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);
            }
        }
    }
}

おすすめ

転載: blog.csdn.net/zt13502162671/article/details/105051352