过滤器

  • 目录
  • 消息拦截器——全局只要按照路由访问的接口都可以拦截
  • 过滤器——在项目中全局AOP实现过滤器
  • 异常过滤——在项目中全局AOP实现过滤器

消息拦截器——全局只要按照路由访问的接口都可以拦截

    /// <summary>  
    /// HTTP消息拦截器  
    /// </summary>  
    public class RequestHandler : DelegatingHandler
    {
        /// <summary>  
        /// 拦截请求  
        /// </summary>  
        /// <param name="request">请求</param>  
        /// <param name="cancellationToken">用于发送取消操作信号</param>  
        /// <returns></returns>  
        protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //获取URL参数  
            NameValueCollection query = HttpUtility.ParseQueryString(request.RequestUri.Query);
            //获取Post正文数据,比如json文本  
            string fRequesContent = request.Content.ReadAsStringAsync().Result;

            //可以做一些其他安全验证工作,比如Token验证,签名验证。  
            //可以在需要时自定义HTTP响应消息  
            //return SendError("自定义的HTTP响应消息", HttpStatusCode.OK);  

            //请求处理耗时跟踪  
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //调用内部处理接口,并获取HTTP响应消息  
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
            //篡改HTTP响应消息正文  
            response.Content = new StringContent(response.Content.ReadAsStringAsync().Result.Replace(@"\\", @"\"));
            if (!response.IsSuccessStatusCode)
            {
                using (var httpClient = new HttpClient())
                {
                    //response = await httpClient.PostAsync("http://www.subaotech.com:8002/api/TestTengFei/GetUrlData", request.RequestUri.AbsolutePath.Split('?')[0], new System.Net.Http.Formatting.JsonMediaTypeFormatter());
                    response = await httpClient.PostAsync("http://localhost:63107/api/TestTengFei/GetUrlData", request.RequestUri.AbsolutePath.Split('?')[0], new System.Net.Http.Formatting.JsonMediaTypeFormatter());
                    sw.Stop();
                    return response;
                }//http://www.subaotech.com:8002/api/TestTengFei/GetUrlData
                //request.RequestUri = new Uri("http://localhost:63107/api/TestTengFei/GetUrlData");
                //HttpResponseMessage response1 = await base.SendAsync(request, cancellationToken);
                //var controller = new Controllers.TestTengFeiController();
                //response1.Content = new StringContent(response1.Content.ReadAsStringAsync().Result.Replace(@"\\", @"\"));
                //response.Content =new StringContent(new Controllers.TestTengFeiController().GetUrlData());
            }
            //var s = response.Content.ReadAsAsync<string>().Result;
            sw.Stop();
            //记录处理耗时  
            long exeMs = sw.ElapsedMilliseconds;
            return response;
        }

        /// <summary>  
        /// 构造自定义HTTP响应消息  
        /// </summary>  
        /// <param name="error"></param>  
        /// <param name="code"></param>  
        /// <returns></returns>  
        private HttpResponseMessage SendError(string error, System.Net.HttpStatusCode code)
        {
            var response = new HttpResponseMessage();
            response.Content = new StringContent(error);
            response.StatusCode = code;
            return response;
        }
}

过滤器——在项目中全局AOP实现过滤器

    /// <summary>
    /// 过滤器
    /// </summary>
    public class ControllerFiltertAttributeConfig : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            //HttpContext.Current.Response.Write("{\"id\":1,\"name\":\"小明\"}");
            创建响应对象,初始化为成功,没有指定的话本次请求将不会被拦截
            //actionExecutedContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }
    }

异常过滤——在项目中全局AOP实现过滤器

    /// <summary>
    /// 异常处理
    /// </summary>
    public class ControllerExceptionAttributeConfig : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var message = actionExecutedContext.Exception.Message.ToString();
            message += "\r\n【请求接口】" + actionExecutedContext.ActionContext.Request.RequestUri.ToString();
            message += "\r\n【请求参数】" + JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments);
            LogRecord.WriterErrorLog(message);
            //throw new Exception(actionExecutedContext.Exception.Message);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值