Esempio n. 1
0
        public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
        {
            if (!EndpointHost.ApplyPreRequestFilters(httpReq, httpRes))
            {
                var operationList = (from r in EndpointHost.Config.MetadataMap[_servicePath].Operations
                                     let sampleObjects = (ServiceUtils.IsCheckHealthOperation(operationName) ?
                                                          SampleObjects.CheckHealthSampleMessage :
                                                          SampleObjects.GetSampleMessage(_servicePath, r.Name)) ??
                                                         new SampleMessage(r.RequestType.CreateInstance(), r.ResponseType.CreateInstance())
                                                         let requestObject = ReflectionUtils.PopulateObject(sampleObjects.Request)
                                                                             let responseObject = ReflectionUtils.PopulateObject(sampleObjects.Response)
                                                                                                  select new
                {
                    Name = r.Name,
                    RequestMessage = new
                    {
                        Xml = XmlSerializeToString(requestObject),
                        Json = WrappedJsonSerializer.Instance.SerializeToString(requestObject),
                    },
                    ResponseMessage = new
                    {
                        Xml = XmlSerializeToString(responseObject),
                        Json = WrappedJsonSerializer.Instance.SerializeToString(responseObject),
                    }
                }).OrderBy(item => item.Name).ToList();

                httpRes.ContentType = "application/json";
                httpRes.Write(WrappedJsonSerializer.Instance.SerializeToString(operationList));
            }
        }
Esempio n. 2
0
        public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
        {
            if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes))
            {
                return;
            }

            var response = from o in EndpointHost.Config.MetadataMap[httpReq.ServicePath].Operations
                           orderby o.Name ascending
                           select new
            {
                Operation = o.Name,
                Routes    = o.Routes.Select(r => new { Path = r.Path, AllowedVerbs = r.AllowedVerbs ?? "*" }).ToList()
            };

            httpRes.ContentType = "application/json";
            httpRes.Write(WrappedJsonSerializer.Instance.SerializeToString(response.ToList()));
        }
Esempio n. 3
0
        protected Message ExecuteMessage(Message message, EndpointAttributes endpointAttributes, IHttpRequest httpRequest, IHttpResponse httpResponse)
        {
            var soapFeature = endpointAttributes.ToSoapFeature();

            EndpointHost.Config.AssertFeatures(soapFeature);

            var httpReq = HttpContext.Current != null && httpRequest == null
                    ? new HttpRequestWrapper(HttpContext.Current.Request)
                    : httpRequest;
            var httpRes = HttpContext.Current != null && httpResponse == null
                ? new HttpResponseWrapper(HttpContext.Current.Response)
                : httpResponse;

            if (httpReq == null)
            {
                throw new ArgumentNullException("httpRequest");
            }

            if (httpRes == null)
            {
                throw new ArgumentNullException("httpResponse");
            }

            if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes))
            {
                return(PrepareEmptyResponse(message, httpReq));
            }

            var    requestMsg  = message ?? GetRequestMessageFromStream(httpReq.InputStream);
            string requestXml  = GetRequestXml(requestMsg);
            var    requestType = GetRequestType(requestMsg, requestXml);

            if (!EndpointHost.Metadata.CanAccess(endpointAttributes, soapFeature.ToFormat(), requestType.Name))
            {
                throw EndpointHost.Config.UnauthorizedAccess(endpointAttributes);
            }

            try
            {
                var useXmlSerializerRequest = requestType.HasAttribute <XmlSerializerFormatAttribute>();

                var request = useXmlSerializerRequest
                                  ? XmlSerializableDeserializer.Instance.Parse(requestXml, requestType)
                                  : DataContractDeserializer.Instance.Parse(requestXml, requestType);

                var requiresSoapMessage = request as IRequiresSoapMessage;
                if (requiresSoapMessage != null)
                {
                    requiresSoapMessage.Message = requestMsg;
                }

                httpReq.OperationName = requestType.Name;
                httpReq.SetItem("SoapMessage", requestMsg);

                var hasRequestFilters = EndpointHost.RequestFilters.Count > 0 ||
                                        FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any();

                if (hasRequestFilters && EndpointHost.ApplyRequestFilters(httpReq, httpRes, request))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var response = ExecuteService(request, endpointAttributes, httpReq, httpRes);

                var hasResponseFilters = EndpointHost.ResponseFilters.Count > 0 ||
                                         FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any();

                if (hasResponseFilters && EndpointHost.ApplyResponseFilters(httpReq, httpRes, response))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var httpResult = response as IHttpResult;
                if (httpResult != null)
                {
                    response = httpResult.Response;
                }

                var useXmlSerializerResponse = response.GetType().HasAttribute <XmlSerializerFormatAttribute>();

                if (useXmlSerializerResponse)
                {
                    return(requestMsg.Headers.Action == null
                        ? Message.CreateMessage(requestMsg.Version, null, response, new XmlSerializerWrapper(response.GetType()))
                        : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response, new XmlSerializerWrapper(response.GetType())));
                }

                return(requestMsg.Headers.Action == null
                    ? Message.CreateMessage(requestMsg.Version, null, response)
                    : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response));
            }
            catch (Exception ex)
            {
                throw new SerializationException("3) Error trying to deserialize requestType: "
                                                 + requestType
                                                 + ", xml body: " + requestXml, ex);
            }
        }
Esempio n. 4
0
        protected Message ExecuteMessage(Message requestMsg, EndpointAttributes endpointAttributes, IHttpRequest httpRequest, IHttpResponse httpResponse)
        {
            if ((EndpointAttributes.Soap11 & this.HandlerAttributes) == EndpointAttributes.Soap11)
            {
                EndpointHost.Config.AssertFeatures(Feature.Soap11);
            }
            else if ((EndpointAttributes.Soap12 & this.HandlerAttributes) == EndpointAttributes.Soap12)
            {
                EndpointHost.Config.AssertFeatures(Feature.Soap12);
            }

            string requestXml;

            using (var reader = requestMsg.GetReaderAtBodyContents())
            {
                requestXml = reader.ReadOuterXml();
            }

            var requestType = GetRequestType(requestMsg, requestXml);

            try
            {
                var request             = DataContractDeserializer.Instance.Parse(requestXml, requestType);
                var requiresSoapMessage = request as IRequiresSoapMessage;
                if (requiresSoapMessage != null)
                {
                    requiresSoapMessage.Message = requestMsg;
                }

                var httpReq = HttpContext.Current != null
                    ? new HttpRequestWrapper(requestType.Name, HttpContext.Current.Request)
                    : httpRequest;
                var httpRes = HttpContext.Current != null
                    ? new HttpResponseWrapper(HttpContext.Current.Response)
                    : httpResponse;

                if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var hasRequestFilters = EndpointHost.RequestFilters.Count > 0 ||
                                        FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any();

                if (hasRequestFilters && EndpointHost.ApplyRequestFilters(httpReq, httpRes, request))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var response = ExecuteService(request, endpointAttributes, httpReq, httpRes);

                var hasResponseFilters = EndpointHost.ResponseFilters.Count > 0 ||
                                         FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any();

                if (hasResponseFilters && EndpointHost.ApplyResponseFilters(httpReq, httpRes, response))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var httpResult = response as IHttpResult;
                if (httpResult != null)
                {
                    response = httpResult.Response;
                }

                return(requestMsg.Headers.Action == null
                                        ? Message.CreateMessage(requestMsg.Version, null, response)
                                        : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response));
            }
            catch (Exception ex)
            {
                throw new SerializationException("3) Error trying to deserialize requestType: "
                                                 + requestType
                                                 + ", xml body: " + requestXml, ex);
            }
        }
        public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
        {
            DataFormat format = httpReq.ContentType.ToDataFormat();

            if (format == DataFormat.NotSupported)
            {
                format = httpReq.QueryString["format"].ToDataFormat();
            }
            HttpMethodEnum   method          = httpReq.HttpMethod.ToHttpMethod();
            ICustomOperation customOperation = CustomOperations[httpReq.ServicePath][RestPath];
            AckCodeType?     ack             = AckCodeType.Success;

            try
            {
                if (method == HttpMethodEnum.NotSupported)
                {
                    throw new NotSupportedException("HTTP Method " + method + " is not supported.");
                }
                if (format == DataFormat.NotSupported)
                {
                    throw new NotSupportedException("Data Transfer Format is not supported.");
                }

                if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes))
                {
                    ack = null;
                    return;
                }

                if (customOperation.RequestDTOType != null)
                {
                    if (method == HttpMethodEnum.POST || method == HttpMethodEnum.PUT)
                    {
                        if (httpReq.InputStream.Length > 0)
                        {
                            using (Stream stream = httpReq.InputStream)
                            {
                                httpReq.RequestObject = GeneralSerializer.Deserialize(customOperation.RequestDTOType, stream, format);
                            }
                        }
                    }
                    else
                    {
                        bool hasOnlyFormatParam = httpReq.QueryString.Count == 1 && httpReq.QueryString["format"] != null;
                        if (httpReq.QueryString.Count > 0 && !hasOnlyFormatParam)
                        {
                            httpReq.RequestObject = GeneralSerializer.DeserializeFromQueryString(customOperation.RequestDTOType, httpReq.QueryString);
                        }
                    }
                }

                if (!customOperation.IsValidRequest(httpReq, httpReq.RequestObject))
                {
                    throw new UnauthorizedAccessException("Not allowed.");
                }

                httpRes.ContentType = format.ToContentType();
                object responseObject = customOperation.ExecuteOperation(httpReq, httpReq.RequestObject);
                if (responseObject == null)
                {
                    return;
                }

                if (EndpointHost.Config.MetadataMap[ServicePath].UseChunkedTransferEncoding)
                {
                    httpRes.AddHeader(ServiceUtils.ResponseStatusHttpHeaderKey, ack.Value.ToString());
                    EndpointsExtensions.HttpResponseExtensions.UseChunkedTransferEncoding(httpRes);
                }

                using (Stream stream = httpRes.OutputStream)
                {
                    GeneralSerializer.Serialize(responseObject, stream, format);
                }
            }
            catch (Exception ex)
            {
                ack = AckCodeType.Failure;
                ErrorUtils.LogError("Custom Operation Error", httpReq, ex, true, "FXD300008");
                httpRes.StatusCode = EndpointsExtensions.HttpResponseExtensions.ToStatusCode(ex);
            }
            finally
            {
                if (ack.HasValue)
                {
                    if (!EndpointsExtensions.HttpResponseExtensions.UsedChunkedTransferEncoding(httpRes))
                    {
                        httpRes.AddHeader(ServiceUtils.ResponseStatusHttpHeaderKey, ack.Value.ToString());
                    }

                    httpRes.LogRequest(httpReq);
                }

                HostContext.Instance.EndRequest();
            }
        }
Esempio n. 6
0
        public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
        {
            if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes))
            {
                return;
            }

            List <KeyValuePair <string, object> > configInfo = new List <KeyValuePair <string, object> >();

            if (AppHostBase.Instance != null)
            {
                configInfo.Add(new KeyValuePair <string, object>("StartUpTime", AppHostBase.Instance.StartUpTime));
            }

            if (AppHostHttpListenerBase.Instance != null)
            {
                configInfo.Add(new KeyValuePair <string, object>("StartUpTime", AppHostHttpListenerBase.Instance.StartUpTime));
            }

            configInfo.Add(new KeyValuePair <string, object>("AppId", ServiceUtils.AppId));

            configInfo.Add(new KeyValuePair <string, object>("IPv4", ServiceUtils.HostIP));

            configInfo.Add(new KeyValuePair <string, object>("MachineName", ServiceUtils.MachineName));

            configInfo.Add(new KeyValuePair <string, object>("SOA.CurrentEnv", EnvironmentUtility.CurrentEnv));

            var metadata = EndpointHost.MetadataMap[httpReq.ServicePath];

            configInfo.Add(new KeyValuePair <string, object>("SOA.ServiceName", metadata.ServiceName));
            configInfo.Add(new KeyValuePair <string, object>("SOA.ServiceNamespace", metadata.ServiceNamespace));
            configInfo.Add(new KeyValuePair <string, object>("SOA.ServiceTestSubEnv", metadata.ServiceTestSubEnv ?? "null"));


            configInfo.Add(new KeyValuePair <string, object>(
                               ServiceMetadata.DefaultLogErrorWithRequestInfoSettingKey,
                               metadata.LogErrorWithRequestInfo));

            configInfo.Add(new KeyValuePair <string, object>(
                               ServiceMetadata.DefaultLogCommonRequestInfoSettingKey,
                               metadata.LogCommonRequestInfo));
            configInfo.Add(new KeyValuePair <string, object>(
                               ServiceMetadata.DefaultLogH5HeadExtensionDataSettingKey,
                               metadata.LogH5HeadExtensionData));

            bool circuitBreakerForceClosed = metadata.CircuitBreakerForceClosed;

            configInfo.Add(new KeyValuePair <string, object>(ServiceMetadata.DefaultCircuitBreakerForceClosedSettingKey, circuitBreakerForceClosed));

            Dictionary <string, double> timeoutMap = new Dictionary <string, double>();

            foreach (Operation operation in metadata.Operations)
            {
                timeoutMap.Add(operation.Name, operation.HystrixCommand.GetExecutionTimeout().TotalMilliseconds);
            }
            configInfo.Add(new KeyValuePair <string, object>(ServiceMetadata.DefaultOperationTimeoutMapSettingKey, timeoutMap));

            configInfo.Add(new KeyValuePair <string, object>(
                               ServiceMetadata.DefaultUseChunkedTransferEncodingSettingKey, metadata.UseChunkedTransferEncoding));

            configInfo.Add(new KeyValuePair <string, object>("SOA.FxConfigWebServiceUtils.Enabled", AntFxConfigWebServiceUtils.Enabled));
            configInfo.Add(new KeyValuePair <string, object>("SOA.FxConfigWebServiceUtils.ApiUrl", AntFxConfigWebServiceUtils.ConfigWebServiceApiUrl));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MinGlobalDefaultTimeout", HystrixCommandHelper.MinGlobalDefaultCircuitBreakerTimeoutSetting.TotalMilliseconds.ToString()));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.GlobalDefaultTimeout",
                               HystrixCommandHelper.GlobalDefaultCircuitBreakerTimeoutSetting.HasValue ? HystrixCommandHelper.GlobalDefaultCircuitBreakerTimeoutSetting.Value.TotalMilliseconds.ToString() : null));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.FrameworkDefaultTimeout", HystrixPropertiesCommandDefault.DefaultExecutionIsolationThreadTimeout.TotalMilliseconds.ToString()));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.FrameworkDefaultConnectionMaxRequestCount", ServiceMetadata.FrameworkDefaultConnectionMaxRequestCount));
            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MinConnectionMaxRequestCount", ServiceMetadata.MinConnectionMaxRequestCount));
            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.CheckConnectionMaxRequestCount", metadata.CheckConnectionMaxRequestCount));
            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.ConnectionMaxRequestCount", metadata.ConnectionMaxRequestCount));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.RequestLogMaxSize", MessageLogConfig.RequestLogMaxSize));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.ResponseLogMaxSize", MessageLogConfig.ResponseLogMaxSize));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.FrameworkDefalut.Test", MessageLogConfig.FrameworkDefalutMessageLogConfigOfTestEnv));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.FrameworkDefalut.Uat", MessageLogConfig.FrameworkDefalutMessageLogConfigOfUatEnv));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.FrameworkDefalut.Prod", MessageLogConfig.FrameworkDefalutMessageLogConfigOfProdEnv));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.FrameworkDefalut.Null", MessageLogConfig.FrameworkDefalutMessageLogConfigOfNullEnv));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.FrameworkDefault.Current", MessageLogConfig.CurrentFrameworkDefaultMessageLogConfig));

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.Service", metadata.ServiceMessageLogConfig));

            var operationMessageConfigs = from operation in metadata.Operations
                                          select new
            {
                operation.Name,
                operation.OperationMessageLogConfig,
            };

            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.MessageLogConfig.Operation", operationMessageConfigs));
            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.DeserializeRequestUseMemoryStream", metadata.DeserializeRequestUseMemoryStream));
            configInfo.Add(new KeyValuePair <string, object>(
                               "SOA.LogPopulateExceptionAsWarning", ReflectionUtils.LogPopulateExceptionAsWarning));

            foreach (IHasConfigInfo configInfoOwner in ConfigInfoOwners)
            {
                configInfo.AddRange(configInfoOwner.GetConfigInfo(httpReq.ServicePath));
            }

            using (JsConfigScope scope = JsConfig.BeginScope())
            {
                scope.ExcludeTypeInfo = true;
                scope.DateHandler     = JsonDateHandler.LongDateTime;
                httpRes.ContentType   = "application/json";
                httpRes.Write(WrappedJsonSerializer.Instance.SerializeToString(configInfo));
            }
        }