Exemplo n.º 1
0
        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
        {
            Contract.Assert(httpContextBase != null);

            HttpRequestBase    requestBase = httpContextBase.Request;
            HttpMethod         method      = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
            Uri                uri         = requestBase.Url;
            HttpRequestMessage request     = new HttpRequestMessage(method, uri);

            // Choose a buffered or bufferless input stream based on user's policy
            IHostBufferPolicySelector policySelector = _bufferPolicySelector.Value;
            bool isInputBuffered = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);

            if (isInputBuffered)
            {
                request.Content = new LazyStreamContent(() => requestBase.InputStream);
            }
            else
            {
                request.Content = new LazyStreamContent(() => requestBase.GetBufferlessInputStream());
            }

            foreach (string headerName in requestBase.Headers)
            {
                string[] values = requestBase.Headers.GetValues(headerName);
                AddHeaderToHttpRequestMessage(request, headerName, values);
            }

            // Add context to enable route lookup later on
            request.SetHttpContext(httpContextBase);

            HttpRequestContext requestContext = new WebHostHttpRequestContext(httpContextBase, requestBase, request);

            request.SetRequestContext(requestContext);

            IDictionary httpContextItems = httpContextBase.Items;

            // Add the OWIN environment, when available (such as when using the OWIN integrated pipeline HTTP module).
            if (httpContextItems != null && httpContextItems.Contains(OwinEnvironmentHttpContextKey))
            {
                request.Properties.Add(OwinEnvironmentKey, httpContextItems[OwinEnvironmentHttpContextKey]);
            }

            // The following three properties are set for backwards compatibility only. The request context controls
            // the behavior for all cases except when accessing the property directly by key.

            // Add the retrieve client certificate delegate to the property bag to enable lookup later on
            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);

            // Add information about whether the request is local or not
            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => requestBase.IsLocal));

            // Add information about whether custom errors are enabled for this request or not
            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy <bool>(() => !httpContextBase.IsCustomErrorEnabled));

            return(request);
        }
Exemplo n.º 2
0
        public static string GetHttpVerb(MethodInfo method)
        {
            var verbs = HttpMethodHelper.ConventionalPrefixes.Keys.Select(prefix => $"Http{prefix}").ToList();
            var verb  = method.Attributes.FirstOrDefault(attr => verbs.Contains(attr, StringComparer.InvariantCultureIgnoreCase));

            if (verb == null)
            {
                verb = HttpMethodHelper.GetConventionalVerbForMethodName(method.Name);
                return($"Http{Char.ToUpper(verb[0])}{verb.Substring(1).ToLower()}");
            }
            else
            {
                return(verb);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Get the route string of the specified method
        /// This implementation refers to https://github.com/abpframework/abp/blob/88a32fd4a49b4204c608cafffbf419156148935a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs#L300
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string GetRoute(MethodInfo method)
        {
            string url = String.Empty;

            //Add {id} path if needed
            var idParameterModel = method.Parameters.FirstOrDefault(param => param.Name == "id");

            if (idParameterModel != null)
            {
                var type = Type.GetType(idParameterModel.FullType);
                if (type != null && TypeHelper.IsPrimitiveExtended(type, includeEnums: true))
                {
                    url += "/{id}";
                }
                else
                {
                    // For the composite key, the type is null here, so we can not use reflection,
                    // use ParameterSymbol.Type.GetMembers instead
                    var properties = idParameterModel.ParameterSymbol.Type.GetMembers().OfType <IPropertySymbol>();

                    foreach (var property in properties)
                    {
                        url += "/{" + property.Name + "}";
                    }
                }
            }

            //Add action name if needed
            string actionNameInUrl = HttpMethodHelper.RemoveHttpMethodPrefix(method.Name, HttpMethodHelper.GetConventionalVerbForMethodName(method.Name))
                                     .RemovePostFix("Async")
            ;

            if (!actionNameInUrl.IsNullOrEmpty())
            {
                url += $"/{actionNameInUrl.ToCamelCase()}";

                //Add secondary Id
                var secondaryIds = method.Parameters.Where(p => p.Name.EndsWith("Id", StringComparison.Ordinal)).ToList();
                if (secondaryIds.Count == 1)
                {
                    url += $"/{{{secondaryIds[0].Name}}}";
                }
            }

            return(url.RemovePreFix("/"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Get the route string of the specified method
        /// This implementation refers to https://github.com/abpframework/abp/blob/88a32fd4a49b4204c608cafffbf419156148935a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs#L300
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string GetRoute(MethodInfo method)
        {
            string url = String.Empty;

            //Add {id} path if needed
            var idParameterModel = method.Parameters.FirstOrDefault(param => param.Name == "id");

            if (idParameterModel != null)
            {
                var type = Type.GetType(idParameterModel.FullType) !;
                if (TypeHelper.IsPrimitiveExtended(type, includeEnums: true))
                {
                    url += "/{id}";
                }
                else
                {
                    var properties = type
                                     .GetProperties(BindingFlags.Instance | BindingFlags.Public);

                    foreach (var property in properties)
                    {
                        url += "/{" + property.Name + "}";
                    }
                }
            }

            //Add action name if needed
            string actionNameInUrl = HttpMethodHelper.RemoveHttpMethodPrefix(method.Name, HttpMethodHelper.GetConventionalVerbForMethodName(method.Name))
                                     .RemovePostFix("Async")
            ;

            if (!actionNameInUrl.IsNullOrEmpty())
            {
                url += $"/{actionNameInUrl.ToCamelCase()}";

                //Add secondary Id
                var secondaryIds = method.Parameters.Where(p => p.Name.EndsWith("Id", StringComparison.Ordinal)).ToList();
                if (secondaryIds.Count == 1)
                {
                    url += $"/{{{secondaryIds[0].Name}}}";
                }
            }

            return(url.RemovePreFix("/"));
        }
        protected virtual string NormalizeUrlActionName(string rootPath, string controllerName, ActionModel action, string httpMethod, [CanBeNull] ConventionalControllerSetting configuration)
        {
            var actionNameInUrl = HttpMethodHelper
                                  .RemoveHttpMethodPrefix(action.ActionName, httpMethod)
                                  .RemovePostFix("Async");

            if (configuration?.UrlActionNameNormalizer == null)
            {
                return(actionNameInUrl);
            }

            return(configuration.UrlActionNameNormalizer(
                       new UrlActionNameNormalizerContext(
                           rootPath,
                           controllerName,
                           action,
                           actionNameInUrl,
                           httpMethod
                           )
                       ));
        }
        private void AddBody(ApiRequest <TRequest> request, IRestRequest apiRequest)
        {
            if (request.Context.Method.HasValue == true &&
                HttpMethodHelper.HasRequestBody(request.Context.Method.Value) == true)
            {
                switch (request.Context.ContentType)
                {
                case null:
                case ContentType.Json:
                    _ = apiRequest.AddJsonBody(request.Model);
                    break;

                case ContentType.FormUrlEncoded:
                    AddFormUrlEncodedBody(request, apiRequest);
                    break;

                default:
                    throw new InvalidOperationException("Unsupported value");
                }
            }
        }
        private static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
        {
            Contract.Assert(httpContextBase != null);

            HttpRequestBase    requestBase = httpContextBase.Request;
            HttpMethod         method      = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
            Uri                uri         = requestBase.Url;
            HttpRequestMessage request     = new HttpRequestMessage(method, uri);

            // TODO: Should we use GetBufferlessInputStream? Yes, as we don't need any of the parsing from ASP
            request.Content = new StreamContent(requestBase.InputStream);
            foreach (string headerName in requestBase.Headers)
            {
                string[] values = requestBase.Headers.GetValues(headerName);
                AddHeaderToHttpRequestMessage(request, headerName, values);
            }

            // Add context to enable route lookup later on
            request.Properties.Add(HttpContextBaseKey, httpContextBase);

            return(request);
        }
Exemplo n.º 8
0
        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
        {
            Contract.Assert(httpContextBase != null);

            HttpRequestBase    requestBase = httpContextBase.Request;
            HttpMethod         method      = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
            Uri                uri         = requestBase.Url;
            HttpRequestMessage request     = new HttpRequestMessage(method, uri);

            // Choose a buffered or bufferless input stream based on user's policy
            IHostBufferPolicySelector policySelector = _bufferPolicySelector.Value;
            bool   isInputBuffered = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);
            Stream inputStream     = isInputBuffered
                                    ? requestBase.InputStream
                                    : httpContextBase.ApplicationInstance.Request.GetBufferlessInputStream();

            request.Content = new StreamContent(inputStream);
            foreach (string headerName in requestBase.Headers)
            {
                string[] values = requestBase.Headers.GetValues(headerName);
                AddHeaderToHttpRequestMessage(request, headerName, values);
            }

            // Add context to enable route lookup later on
            request.Properties.Add(HttpContextBaseKey, httpContextBase);

            // Add the retrieve client certificate delegate to the property bag to enable lookup later on
            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);

            // Add information about whether the request is local or not
            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => requestBase.IsLocal));

            // Add information about whether custom errors are enabled for this request or not
            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy <bool>(() => !httpContextBase.IsCustomErrorEnabled));

            return(request);
        }
Exemplo n.º 9
0
        private static Message ConfigureRequestMessage(Message message)
        {
            if (message == null)
            {
                return(null);
            }

            HttpRequestMessageProperty requestProperty;

            if (!message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out requestProperty))
            {
                throw Error.InvalidOperation(
                          SRResources.RequestMissingHttpRequestMessageProperty,
                          HttpRequestMessageProperty.Name,
                          typeof(HttpRequestMessageProperty).Name);
            }

            Uri uri = message.Headers.To;

            if (uri == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMissingToHeader);
            }

            HttpRequestMessage httpRequestMessage = message.ToHttpRequestMessage();

            if (httpRequestMessage == null)
            {
                if (!message.IsEmpty)
                {
                    throw Error.InvalidOperation(SRResources.NonHttpMessageMustBeEmpty, HttpMessageExtensions.ToHttpRequestMessageMethodName, typeof(HttpMessage).Name);
                }

                httpRequestMessage = new HttpRequestMessage();
                Message oldMessage = message;
                message = httpRequestMessage.ToMessage();
                message.Properties.CopyProperties(oldMessage.Properties);
                oldMessage.Close();
            }
            else
            {
                // Clear headers but not properties.
                message.Headers.Clear();
            }

            // Copy message properties to HttpRequestMessage. While it does have the
            // risk of allowing properties to get out of sync they in virtually all cases are
            // read-only so the risk is low. The downside to not doing it is that it isn't
            // possible to access anything from HttpRequestMessage (or OperationContent.Current)
            // which is worse.
            foreach (KeyValuePair <string, object> kv in message.Properties)
            {
                httpRequestMessage.Properties.Add(kv.Key, kv.Value);
            }

            if (httpRequestMessage.Content == null)
            {
                httpRequestMessage.Content = new ByteArrayContent(new byte[0]);
            }
            else
            {
                httpRequestMessage.Content.Headers.Clear();
            }

            message.Headers.To = uri;

            httpRequestMessage.RequestUri = uri;
            httpRequestMessage.Method     = HttpMethodHelper.GetHttpMethod(requestProperty.Method);

            foreach (var headerName in requestProperty.Headers.AllKeys)
            {
                string headerValue = requestProperty.Headers[headerName];
                if (!httpRequestMessage.Headers.TryAddWithoutValidation(headerName, headerValue))
                {
                    httpRequestMessage.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
                }
            }

            return(message);
        }
Exemplo n.º 10
0
 protected virtual string SelectHttpMethod(ActionModel action, ConventionalControllerSetting configuration)
 {
     return(HttpMethodHelper.GetConventionalVerbForMethodName(action.ActionName));
 }
Exemplo n.º 11
0
 public HttpMethod GetHttpMethod()
 {
     return(HttpMethodHelper.ConvertToHttpMethod(HttpMethod));
 }
Exemplo n.º 12
0
 public override string ToString()
 {
     return(string.Format("{0} {1} HTTP/{2}\r\n", HttpMethodHelper.GetString(Method), RequestUri, HttpVersion.ToString()));
 }