• Webapi中messagehandler


    /// <summary>
        ///  API消息请求处理
        /// </summary>
        public class MessageHandler : MessageProcessingHandler
        {
    
    
            /// <summary>
            /// 接收到request时 处理
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
    
            protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var contentType = request.Content.Headers.ContentType;
    
    
    
                Stopwatch stopwatch = new Stopwatch();
    
                var data = System.Web.HttpContext.Current.Request["data"];
    
                if (!string.IsNullOrWhiteSpace(data))
                {
                    try
                    {
    
                        if (request.Method == HttpMethod.Post)
                        {
                            request.Content = new StringContent(data, Encoding.UTF8, "application/json");
                            var route = request.GetRouteData();
                            route.Values.Add("signdata", data);
                        }
                        else
                        {
                            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, string>>(data);
                            string baseQuery = "";
                            foreach (var kv in obj)
                            {
                                baseQuery += kv.Key + "=" + kv.Value + "&";
                            }
                            baseQuery = baseQuery.TrimEnd('&');
                            request.RequestUri = new Uri($"{request.RequestUri.AbsoluteUri.Split('?')[0]}?{baseQuery}");
                            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                        }
                    } catch (Exception ex)
                    {
                        request.Content = new StringContent("", Encoding.UTF8, "application/json");
                        request.CreateResponse(HttpStatusCode.Gone, "Exception");
    
                        return request;
                    }
                }
                return request;
            }
            /// <summary>
            /// 处理将要向客户端response时
            /// </summary>
            /// <param name="response"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
    
            protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)
            {
    
    
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var result = response.Content.ReadAsStringAsync();
                    result.Wait();
                    var resultData = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultData<object>>(result.Result);
                    if (resultData != null)
    { if (resultData.Code == 200 )
    { var timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; var encodeResult = Newtonsoft.Json.JsonConvert.SerializeObject(resultData.Data, Newtonsoft.Json.Formatting.None, timeConverter);
    resultData.Data = encodeResult;
    response.Content = new ObjectContent<ResultData<object>>(resultData, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
    } } } return response; } }
     /// <summary>
        /// 不启用签名验证
        /// </summary>
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
        public class NoCheckSign : Attribute { }
        /// <summary>
        /// Sign验证器
        /// </summary>
        public class CheckSignFilter : ActionFilterAttribute
        {
            /// <summary>
            /// 验证参数的签名
            /// </summary>
            /// <param name="actionContext"></param>
            public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
            {
                base.OnActionExecuting(actionContext);
          
                var attributes = actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<NoCheckSign>();
                if (attributes.Count >= 1){  return;}
    
                attributes = actionContext.ActionDescriptor.GetCustomAttributes<NoCheckSign>();
                if (attributes.Count>= 1){return;}
                HttpRequest request = HttpContext.Current.Request;
                string sign = request["sign"];
                
                var data = actionContext.Request.GetRouteData().Values["signdata"] as string;
                if (  string.IsNullOrWhiteSpace(data) )
                {
                    actionContext.Response = GetSignFailResult();
                    return;
                }
     
                string signdata = data;//TODO具体的验签处理
                if (!string.Equals(signdata, sign, StringComparison.OrdinalIgnoreCase))
                {
                    actionContext.Response = GetSignFailResult();
                    return;
                }
            }
           
            private HttpResponseMessage GetSignFailResult()
            {
                ResultData<object> result = new ResultData<object>();
                result.Code =403;
                result.Msg = "SignErroo";
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent(result.GetType(), result, new JsonMediaTypeFormatter())
                };
                return response;
            }
        }
    }

    /// <summary>    ///  API消息请求处理    /// </summary>    public class MessageHandler : MessageProcessingHandler    {

            /// <summary>        /// 接收到request时 处理        /// </summary>        /// <param name="request"></param>        /// <param name="cancellationToken"></param>        /// <returns></returns>
            protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)        {            var contentType = request.Content.Headers.ContentType;


                Stopwatch stopwatch = new Stopwatch();
                var data = System.Web.HttpContext.Current.Request["data"];
                if (!string.IsNullOrWhiteSpace(data))            {                try                {
                        if (request.Method == HttpMethod.Post)                    {                        request.Content = new StringContent(data, Encoding.UTF8, "application/json");                        var route = request.GetRouteData();                        route.Values.Add("signdata", data);                    }                    else                    {                        var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, string>>(data);                        string baseQuery = "";                        foreach (var kv in obj)                        {                            baseQuery += kv.Key + "=" + kv.Value + "&";                        }                        baseQuery = baseQuery.TrimEnd('&');                        request.RequestUri = new Uri($"{request.RequestUri.AbsoluteUri.Split('?')[0]}?{baseQuery}");                        request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");                    }                } catch (Exception ex)                {                    request.Content = new StringContent("", Encoding.UTF8, "application/json");                    request.CreateResponse(HttpStatusCode.Gone, "Exception");
                        return request;                }            }            return request;        }        /// <summary>        /// 处理将要向客户端response时        /// </summary>        /// <param name="response"></param>        /// <param name="cancellationToken"></param>        /// <returns></returns>
            protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)        {

                if (response.StatusCode == HttpStatusCode.OK)            {                var result = response.Content.ReadAsStringAsync();                result.Wait();                var baseResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultData<object>>(result.Result);                if (baseResult != null)                {                    if (baseResult.Code == ViewModel.ResultCode.Success && baseResult.Data != null )                    {                        var timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };                        var encodeResult =  Newtonsoft.Json.JsonConvert.SerializeObject(baseResult.Data, Newtonsoft.Json.Formatting.None, timeConverter);
                                                   baseResult.Data = encodeResult;                        response.Content = new ObjectContent<BaseResult<object>>(baseResult, new System.Net.Http.Formatting.JsonMediaTypeFormatter());                    }

                    }            }                       return response;            }}

  • 相关阅读:
    mybatis公用代码抽取到单独的mapper.xml文件
    mysql与oracle常用函数及数据类型对比00持续补充
    人民币在岸 离岸 中间价的含义与关系
    mysql hang and srv_error_monitor_thread using 100% cpu(已解决)
    long和BigDecimal引发的管理思考
    mybatis 3的TypeHandler深入解析(及null值的处理)
    mysql 5.7.17发布
    rabbitmq connection/channel/consumer/queue的数量关系详细分析
    rabbitMQ publish丢包分析
    INFO: task java:27465 blocked for more than 120 seconds不一定是cache太大的问题
  • 原文地址:https://www.cnblogs.com/itclw/p/15153640.html
Copyright © 2020-2023  润新知