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

上一篇:redis 系列18 事件


下一篇:webAPI编程-04