예제 #1
0
 public HttpRequestModel(HttpOperation owner, HttpProviderAttribute httpClient, HttpPathAttribute httpPath, HttpMethodAttribute httpVerb, HttpTimeoutAttribute httpTimeout, HttpHeaderAttribute[] httpClassHeaders)
 {
     _owner = owner;
     _owner.Log("HttpRequestModel Initializing", LogSeverity.VERBOSE);
     _httpClient       = httpClient;
     _httpPath         = httpPath;
     _httpVerb         = httpVerb;
     _httpTimeout      = httpTimeout;
     _uriTemplates     = new Hashtable();
     _formFields       = new Hashtable();
     _binaryFormFields = new Dictionary <string, HttpBinaryFormField>();
     _httpHeaders      = new Dictionary <string, string>();
     _queryStrings     = new List <DictionaryEntry>();
     _stringBody       = null;
     _binaryBody       = null;
     _owner.Log("Processing class level maps.", LogSeverity.VERBOSE);
     foreach (HttpHeaderAttribute httpHeaderAttribute in httpClassHeaders)
     {
         if (httpHeaderAttribute.MapOnRequest())
         {
             _owner.Log("Processing map '" + httpHeaderAttribute.GetType().FullName + "'.", LogSeverity.VERBOSE);
             httpHeaderAttribute.Initialize();
             string text  = httpHeaderAttribute.OnRequestResolveName(_owner, null);
             object value = httpHeaderAttribute.OnRequestResolveValue(text, _owner, null);
             value = httpHeaderAttribute.OnRequestApplyConverters(value, _owner, null);
             if (!string.IsNullOrEmpty(text))
             {
                 AddHttpHeader(text, (value != null) ? value.ToString() : "");
             }
         }
     }
 }
예제 #2
0
        private MethodInfo GetRunMethod()
        {
            var httpMethodAttribute = HttpMethodAttribute.Get(_type.GetInterfaces().Single(HttpMethodAttribute.IsAppliedTo));
            var method = _type.GetMethod(httpMethodAttribute.Method);

            return(method);
        }
        /// <summary>
        /// Gets the Http method and the template from a <see cref="HttpMethodAttribute"/>.
        /// </summary>
        /// <param name="attr">The <see cref="HttpMethodAttribute"/> instance.</param>
        /// <param name="httpMethod">A variable to receive the <see cref="HttpMethod"/>.</param>
        /// <returns>The attribute template.</returns>
        private static string GetMethodAndTemplateFromAttribute(
            this HttpMethodAttribute attr,
            out HttpMethod httpMethod)
        {
            httpMethod = null;

            if (attr is HttpGetAttribute)
            {
                httpMethod = HttpMethod.Get;
            }
            else if (attr is HttpPostAttribute)
            {
                httpMethod = HttpMethod.Post;
            }
            else if (attr is HttpPutAttribute)
            {
                httpMethod = HttpMethod.Put;
            }
            else if (attr is HttpPatchAttribute)
            {
                httpMethod = new HttpMethod("Patch");
            }
            else if (attr is HttpDeleteAttribute)
            {
                httpMethod = HttpMethod.Delete;
            }

            return(((HttpMethodAttribute)attr).Template);
        }
예제 #4
0
        private static MethodInfo GetMethodInfo(IInvocation invocation, HttpMethodAttribute requestAttribute)
        {
            Type type = null;

            switch (requestAttribute)
            {
            case GetAttribute _:
                type = invocation.Method.ReturnType.GetGenericArguments()[0];
                break;

            case PostAttribute _:
            case PutAttribute _:
            case DeleteAttribute _:
                var bodyAttribute = ParamAttribute <BodyAttribute>(invocation);
                if (bodyAttribute != (null, null))
                {
                    type = bodyAttribute.Value.GetType();
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(requestAttribute));
            }

            var methodName = GetMethodName(requestAttribute);

            var method = type == null?GetMethodInfo(methodName) : GetGenericMethodInfo(methodName, type);

            return(method);
        }
예제 #5
0
 private MethodInfo GetRunMethod(string httpMethod)
 {
     return(_handlerType.GetInterfaces()
            .Where(HttpMethodAttribute.IsAppliedTo)
            .Select(t => HttpMethodAttribute.GetMethod(t, httpMethod))
            .Single(a => a != null));
 }
예제 #6
0
        public static bool MatchRouteTemplate(this HttpMethodAttribute httpMethodAttribute, HttpContext context, IRouteMatcher routeMatcher)
        {
            if (string.IsNullOrEmpty(httpMethodAttribute.Template))
            {
                return(false);
            }

            var match = routeMatcher.Match(httpMethodAttribute.Template, context.Request.Path);

            if (match == null)
            {
                // path doesn't match route template
                return(false);
            }

            // write route data
            var routeData = context.GetRouteData();

            foreach (var item in match)
            {
                routeData.Values.Add(item.Key, item.Value);
            }

            return(true);
        }
        private static HttpMethodAttribute CreateHttpMethodAttribute(HttpMethodAttribute httpMethodAttribute, String controllerTemplate)
        {
            if (httpMethodAttribute is HttpDeleteAttribute)
            {
                return(new HttpDeleteAttribute(controllerTemplate));
            }
            if (httpMethodAttribute is HttpGetAttribute)
            {
                return(new HttpGetAttribute(controllerTemplate));
            }
            if (httpMethodAttribute is HttpHeadAttribute)
            {
                return(new HttpHeadAttribute(controllerTemplate));
            }
            if (httpMethodAttribute is HttpOptionsAttribute)
            {
                return(new HttpOptionsAttribute(controllerTemplate));
            }
            if (httpMethodAttribute is HttpPatchAttribute)
            {
                return(new HttpPatchAttribute(controllerTemplate));
            }
            if (httpMethodAttribute is HttpPostAttribute)
            {
                return(new HttpPostAttribute(controllerTemplate));
            }
            if (httpMethodAttribute is HttpPutAttribute)
            {
                return(new HttpPutAttribute(controllerTemplate));
            }

            throw new InvalidOperationException("Unknown HttpMethodAttribute " + httpMethodAttribute.GetType().FullName);
        }
예제 #8
0
        private static string GetMethodName(HttpMethodAttribute requestAttribute)
        {
            string methodName;

            switch (requestAttribute)
            {
            case GetAttribute _:
                methodName = nameof(HttpExtensions.GetAsync);
                break;

            case PostAttribute _:
                methodName = nameof(HttpExtensions.PostAsync);
                break;

            case PutAttribute _:
                methodName = nameof(HttpExtensions.PutAsync);
                break;

            case DeleteAttribute _:
                methodName = nameof(HttpExtensions.DeleteAsync);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(requestAttribute));
            }

            return(methodName);
        }
예제 #9
0
        private static MethodInfo FindMethod(Type controllerType, string actionName, HttpRequestMethod requestMethod)
        {
            MethodInfo[] methods = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                   .Where(method => method.Name == actionName)
                                   .ToArray();

            foreach (MethodInfo method in methods)
            {
                HttpMethodAttribute httpMethodAttribute = method.GetCustomAttribute <HttpMethodAttribute>();

                if (httpMethodAttribute == null)
                {
                    if (requestMethod == HttpRequestMethod.GET)
                    {
                        return(method);
                    }
                }
                else if (httpMethodAttribute.Accepts(requestMethod))
                {
                    return(method);
                }
            }

            return(null);
        }
예제 #10
0
 private static void AssertAttributeHasName(HttpMethodAttribute hypermediaAttribute)
 {
     if (string.IsNullOrEmpty(hypermediaAttribute.Name))
     {
         throw new RouteRegisterException($"{hypermediaAttribute.GetType().Name} must have a name.");
     }
 }
예제 #11
0
        protected virtual async Task InvokeGetAsync(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            string uri = BuildGetRequestUri(method, httpMethod, args);

            HttpResponseMessage response = await _httpClient.GetAsync(uri);

            ProcessResponseAsync(response, method);
        }
예제 #12
0
        protected virtual async Task <T> InvokeDeleteAsync <T>(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            string uri = BuildDeleteRequestUri(method, httpMethod, args);

            HttpResponseMessage response = await _httpClient.DeleteAsync(uri);

            return(await ProcessResponseAsync <T>(response, method));
        }
예제 #13
0
        private static RoutingTable BuildRoutingTable(string httpMethod)
        {
            var handlerTypes = ExportedTypeHelper.FromCurrentAppDomain(IsHttpMethodHandler)
                               .Where(i => HttpMethodAttribute.Get(i).HttpMethod.Equals(httpMethod, StringComparison.OrdinalIgnoreCase))
                               .ToArray();

            return(new RoutingTableBuilder(handlerTypes).BuildRoutingTable());
        }
예제 #14
0
        protected virtual async Task <T> InvokePutAsync <T>(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            string uri     = GetPutRequestUri(method, httpMethod, args);
            var    content = GetPutRequestContent(method, args);

            HttpResponseMessage response = await _httpClient.PutAsync(uri, content);

            return(await ProcessResponseAsync <T>(response, method));
        }
예제 #15
0
        private bool ValidateMethod(string requestMethod)
        {
            HttpMethodAttribute attr = (HttpMethodAttribute)_info.GetCustomAttributes(
                typeof(HttpMethodAttribute), true).FirstOrDefault();

            string method = attr?.HttpMethods.FirstOrDefault() ?? "POST";

            return(string.Compare(method, requestMethod, true) == 0);
        }
예제 #16
0
        // InvokeGet builds out the URI with route parameters and querystring,
        // then calls GetAsync and processes the HttpResponseMessage

        #region InvokeGet, InvokeGetAsync, InvokeGetAsync<T>

        protected virtual object InvokeGet(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            string uri = BuildGetRequestUri(method, httpMethod, args);

            HttpResponseMessage response = _httpClient.GetAsync(uri)
                                           .GetAwaiter().GetResult(); //synchronous, blocking call.

            return(ProcessResponse(response, method));
        }
예제 #17
0
        // InvokeDelete builds out the URI with route parameters (does not permit querystrings),
        // then calls DeleteAsync and processes the HttpResponseMessage

        #region InvokeDelete, InvokeDeleteAsync, InvokeDeleteAsync<T>

        protected virtual object InvokeDelete(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            string uri = BuildDeleteRequestUri(method, httpMethod, args);

            HttpResponseMessage response = _httpClient.DeleteAsync(uri)
                                           .GetAwaiter().GetResult();

            return(ProcessResponse(response, method));
        }
예제 #18
0
        internal static RoutingTable BuildRoutingTable(string httpMethod)
        {
            var types        = ExportedTypeHelper.FromCurrentAppDomain(IsHttpMethodHandler).ToList();
            var handlerTypes = types
                               .Where(i => HttpMethodAttribute.Matches(i, httpMethod))
                               .ToArray();

            return(new RoutingTableBuilder(handlerTypes).BuildRoutingTable());
        }
예제 #19
0
        private static bool IsExtensionAttribute(HttpMethodAttribute a)
        {
            var attributeType = a.GetType();

            return(attributeType == typeof(HttpGetHypermediaObject) ||
                   attributeType == typeof(HttpPostHypermediaAction) ||
                   attributeType == typeof(HttpDeleteHypermediaAction) ||
                   attributeType == typeof(HttpPatchHypermediaAction) ||
                   attributeType == typeof(HttpGetHypermediaActionParameterInfo));
        }
예제 #20
0
        private void ExecuteHttpRequest(IInvocation invocation, HttpMethodAttribute requestAttribute)
        {
            var routePath = GetRoutePath(invocation, Path, requestAttribute.Path);

            var method = GetMethodInfo(invocation, requestAttribute);

            var result = InvokeHttpRequest(invocation, routePath, method);

            invocation.ReturnValue = result;
        }
예제 #21
0
        public static HttpMethodAttribute GetHttpMethodAttribute(this ActionDescriptor action)
        {
            HttpMethodAttribute attr =
                action
                .EndpointMetadata
                .OfType <HttpMethodAttribute>()
                .First();

            return(attr);
        }
예제 #22
0
        // InvokePut builds out the URI with route parameters (no querystring),
        // then generates the HttpContent payload (if there is one).
        // then calls PutAsync and processes the HttpResponseMessage.
        // It is identical to InvokePost in every way except for calling PutAsync.

        #region InvokePut, InvokePutAsync, InvokePutAsync<T>

        protected virtual object InvokePut(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            string uri     = GetPutRequestUri(method, httpMethod, args);
            var    content = GetPutRequestContent(method, args);

            HttpResponseMessage response = _httpClient.PutAsync(uri, content)
                                           .GetAwaiter().GetResult();

            return(ProcessResponse(response, method));
        }
예제 #23
0
        private string GetPutRequestUri(MethodInfo method, HttpMethodAttribute httpMethod, object[] args)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(method.Name);

            BindRouteParameters(sb, method, httpMethod, args);

            return(sb.ToString());
        }
예제 #24
0
        public RouteActionMatch(Type controller, MethodInfo action, HttpMethodAttribute httpMethod)
        {
            Assert.NotNull(controller, nameof(controller));
            Assert.NotNull(action, nameof(action));
            Assert.NotNull(httpMethod, nameof(httpMethod));

            Controller = controller;
            Action     = action;
            HttpMethod = httpMethod;
        }
예제 #25
0
파일: PimsAssert.cs 프로젝트: sookeke/PIMS
 /// <summary>
 /// Assert that the HTTP method template matches the specified 'template'.
 /// </summary>
 /// <param name="attribute"></param>
 /// <param name="template"></param>
 public static void HasTemplate(this HttpMethodAttribute attribute, string template = null)
 {
     if (template == null)
     {
         Assert.Null(attribute.Template);
     }
     else
     {
         Assert.Equal(template, attribute.Template);
     }
 }
예제 #26
0
        private const int trimLength = 10; // "Controller".Length;

        public HttpActionInformation(Type controller, MethodInfo method, HttpMethodAttribute action, RouteAttribute route = null)
        {
            var template = (route?.Template.TrimEnd('/') + '/' + action.Template).Replace("[controller]", controller.Name.Substring(0, controller.Name.Length - trimLength));

            this.HttpMappings = new ReadOnlyDictionary <string, MethodInfo>(action.HttpMethods.ToDictionary(h => h, h => method));
            this.Name         = action.Name;
            this.Order        = action.Order;
            this.Segments     = template.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(s => new Segment(s)).ToArray();
            this.Template     = template;
            this.AnyRepeating = this.Segments.Any(s => s.IsRepeating);
        }
예제 #27
0
        public void SettingMethod(PathItem pathItem, HttpMethodAttribute method, Operation operation)
        {
            if (method == null)
            {
                if (pathItem.Get == null)
                {
                    pathItem.Get = operation;
                }
                return;
            }

            switch (method.HttpMethods.First().ToLower())
            {
            case "get":
                if (pathItem.Get == null)
                {
                    pathItem.Get = operation;
                }
                break;

            case "put":
                if (pathItem.Put == null)
                {
                    pathItem.Put = operation;
                }
                break;

            case "post":
                if (pathItem.Post == null)
                {
                    pathItem.Post = operation;
                }
                break;

            case "delete":
                if (pathItem.Delete == null)
                {
                    pathItem.Delete = operation;
                }
                break;

            case "patch":
            case "merge":
                if (pathItem.Patch == null)
                {
                    pathItem.Patch = operation;
                }
                break;

            default:
                throw new InvalidOperationException($"HttpMethod {method.Name} is not supported.");
            }
        }
예제 #28
0
 public static string GetMethod(this HttpMethodAttribute attribute)
 {
     if (attribute is HttpPatchAttribute)
     {
         return("GetPatchMethod()");
     }
     else
     {
         string text = attribute.HttpMethods.First();
         return($"HttpMethod.{text.Substring(0, 1)}{text.Substring(1).ToLower()}");
     }
 }
예제 #29
0
파일: Helper.cs 프로젝트: NameIsBad/NetRpc
 public static OperationType ToOperationType(this HttpMethodAttribute httpMethod)
 {
     return(httpMethod.HttpMethod switch
     {
         "POST" => OperationType.Post,
         "GET" => OperationType.Get,
         "PUT" => OperationType.Put,
         "HEAD" => OperationType.Head,
         "OPTIONS" => OperationType.Options,
         "PATCH" => OperationType.Patch,
         "DELETE" => OperationType.Delete,
         _ => throw new ArgumentOutOfRangeException(nameof(httpMethod))
     });
예제 #30
0
파일: PimsAssert.cs 프로젝트: sookeke/PIMS
        /// <summary>
        /// Assert the specified 'endpoint' has the specified method 'template'.
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="template"></param>
        public static void HasMethod(this MethodInfo endpoint, HttpMethod method, string template)
        {
            HttpMethodAttribute attribute = method switch
            {
                HttpMethod.Post => endpoint.GetCustomAttribute <HttpPostAttribute>(),
                HttpMethod.Put => endpoint.GetCustomAttribute <HttpPutAttribute>(),
                HttpMethod.Delete => endpoint.GetCustomAttribute <HttpDeleteAttribute>(),
                HttpMethod.Get => endpoint.GetCustomAttribute <HttpGetAttribute>(),
                _ => endpoint.GetCustomAttribute <HttpGetAttribute>()
            };

            Assert.NotNull(attribute);
            attribute.HasTemplate(template);
        }