예제 #1
0
        public object Intercept(object target, MethodInfo method, object[] @params)
        {
            var httpContext = AspectContext.From(method);

            if (RequestHost == null || string.IsNullOrEmpty(RequestHost))
            {
                if (httpContext.HostAttribute.Host != null && !string.IsNullOrEmpty(httpContext.HostAttribute.Host.OriginalString))
                {
                    RequestHost = httpContext.HostAttribute.Host.OriginalString;
                }
                else
                {
                    throw new ArgumentNullException(nameof(method), "未定义任何请求服务器地址,请在注册时传入BaseUrl或在服务契约添加HttpHost标签");
                }
            }

            var actionContext = new HttpApiActionContext
            {
                HttpApiClient             = this,
                RequestMessage            = new HttpRequestMessage(),
                RouteAttributes           = httpContext.RouteAttributes,
                ApiReturnAttribute        = httpContext.ApiReturnAttribute,
                ApiActionFilterAttributes = httpContext.ApiActionFilterAttributes,
                ApiActionDescriptor       = httpContext.ApiActionDescriptor.Clone() as ApiActionDescriptor
            };

            var parameters = actionContext.ApiActionDescriptor.Parameters;

            for (var i = 0; i < parameters.Length; i++)
            {
                parameters[i].Value = @params[i];
            }

            var apiAction = httpContext.ApiActionDescriptor;

            try
            {
                return(apiAction.Execute(actionContext));
            }
            catch (Exception ex)
            {
                var errMsg = ex.Message;

                while (ex.InnerException != null)
                {
                    errMsg += "--->" + ex.InnerException.Message;
                    ex      = ex.InnerException;
                }
                throw new Exception($"请求远程服务[{actionContext.RequestMessage?.Method.Method}]{actionContext.RequestMessage?.RequestUri.ToString() ?? RequestHost}异常:{errMsg}", ex);
            }
        }