private static void ConfigureCorsEndpointMetadata(ApplicationModel applicationModel)
    {
        foreach (var controller in applicationModel.Controllers)
        {
            var corsOnController = controller.Attributes.OfType <IDisableCorsAttribute>().Any() ||
                                   controller.Attributes.OfType <IEnableCorsAttribute>().Any();

            foreach (var action in controller.Actions)
            {
                var corsOnAction = action.Attributes.OfType <IDisableCorsAttribute>().Any() ||
                                   action.Attributes.OfType <IEnableCorsAttribute>().Any();

                if (!corsOnController && !corsOnAction)
                {
                    // No CORS here.
                    continue;
                }

                foreach (var selector in action.Selectors)
                {
                    var metadata = selector.EndpointMetadata;
                    // Read interface .Count once rather than per iteration
                    var metadataCount = metadata.Count;
                    for (var i = 0; i < metadataCount; i++)
                    {
                        if (metadata[i] is HttpMethodMetadata httpMethodMetadata)
                        {
                            metadata[i] = new HttpMethodMetadata(httpMethodMetadata.HttpMethods, acceptCorsPreflight: true);
                        }
                    }
                }
            }
        }
    }
        private static IEnumerable <string> GetHttpMethods(Endpoint endpoint)
        {
            HttpMethodMetadata metadata = endpoint.Metadata.GetMetadata <HttpMethodMetadata>();

            if (metadata != null)
            {
                return(metadata.HttpMethods);
            }

            return(new[] { "No HttpMethodMetadata" });
        }
Beispiel #3
0
        private static IEnumerable <string> GetHttpMethods(Endpoint endpoint)
        {
            HttpMethodMetadata methodMetadata = endpoint.Metadata.GetMetadata <HttpMethodMetadata>();

            if (methodMetadata != null)
            {
                return(methodMetadata.HttpMethods);
            }

            throw new Exception();
        }
        private static Endpoint CreateEndpoint(HttpMethodMetadata httpMethodMetadata)
        {
            var metadata = new List <object>()
            {
                httpMethodMetadata
            };

            return(new Endpoint(
                       (context) => Task.CompletedTask,
                       new EndpointMetadataCollection(metadata),
                       $"test: {httpMethodMetadata?.HttpMethods[0]}"));
        }
Beispiel #5
0
        private static IEnumerable <string> GetHttpMethods(Endpoint endpoint)
        {
            Contract.Assert(endpoint != null);

            HttpMethodMetadata metadata = endpoint.Metadata.GetMetadata <HttpMethodMetadata>();

            if (metadata != null)
            {
                return(metadata.HttpMethods);
            }

            return(new[] { "N/A" });
        }
Beispiel #6
0
        private static RouteEndpoint CreateEndpoint(string template, HttpMethodMetadata httpMethodMetadata)
        {
            var metadata = new List <object>();

            if (httpMethodMetadata != null)
            {
                metadata.Add(httpMethodMetadata);
            }

            return(new RouteEndpoint(
                       TestConstants.EmptyRequestDelegate,
                       RoutePatternFactory.Parse(template),
                       0,
                       new EndpointMetadataCollection(metadata),
                       $"test: {template}"));
        }
        private static MatcherEndpoint CreateEndpoint(string template, HttpMethodMetadata httpMethodMetadata)
        {
            var metadata = new List <object>();

            if (httpMethodMetadata != null)
            {
                metadata.Add(httpMethodMetadata);
            }

            return(new MatcherEndpoint(
                       MatcherEndpoint.EmptyInvoker,
                       RoutePatternFactory.Parse(template),
                       0,
                       new EndpointMetadataCollection(metadata),
                       $"test: {template}"));
        }
        private static string GetHttpMethod(IODataRoutingMetadata metadata, Endpoint endpoint)
        {
            string method = metadata.HttpMethods.FirstOrDefault();

            if (method != null)
            {
                return(method);
            }

            HttpMethodMetadata methodMetadata = endpoint.Metadata.GetMetadata <HttpMethodMetadata>();

            if (methodMetadata != null)
            {
                return(methodMetadata.HttpMethods.First());
            }

            throw new Exception();
        }
Beispiel #9
0
        public SwaggerEndpointDataSource(IOptions <SwaggerGenOptions> options, string route, bool?asV2 = null)
        {
            _options       = options;
            _routeTemplate = route;
            if (asV2.HasValue)
            {
                _asV2 = asV2.Value;
            }
            else
            {
                _asHtml = true;
            }
            _conventions = new List <Action <EndpointBuilder> >();

            var getMeta = new HttpMethodMetadata(new[] { "GET" });

            _conventions.Add(builder => builder.Metadata.Add(getMeta));
        }
Beispiel #10
0
        public void AddSelector_AddsCors_ForActionsWithCorsAttribute(Type controllerType, string actionName, bool expectedCorsSetting)
        {
            // Arrange
            IEdmModel   model      = new Mock <IEdmModel>().Object;
            MethodInfo  methodInfo = controllerType.GetMethod(actionName);
            ActionModel action     = methodInfo.BuildActionModel();

            action.Controller = ControllerModelHelpers.BuildControllerModel(controllerType);

            // Act
            action.AddSelector("Get", string.Empty, model, new ODataPathTemplate(CountSegmentTemplate.Instance));

            // Assert
            SelectorModel newSelector = action.Selectors.FirstOrDefault();

            Assert.NotNull(newSelector);
            HttpMethodMetadata httpMethodMetadata = newSelector.EndpointMetadata.OfType <HttpMethodMetadata>().FirstOrDefault();

            Assert.NotNull(httpMethodMetadata);
            Assert.Equal(httpMethodMetadata.AcceptCorsPreflight, expectedCorsSetting);
        }
Beispiel #11
0
        /// <summary>
        /// Checks whether the endpoint is matched the relative uri specified int the request info.
        /// </summary>
        /// <param name="routeEndpoint">The route endpoint.</param>
        /// <param name="requestInfo">The request information.</param>
        /// <param name="routeValueDictionary">The route value dictionary.</param>
        /// <returns>
        /// Whether the endpoint matches the request info relative uri.
        /// </returns>
        private static EndpointMatchResult EndpointMatches(RouteEndpoint routeEndpoint, RequestInfo requestInfo, out RouteValueDictionary routeValueDictionary)
        {
            if (!_templateMatcherCache.TryGetValue(routeEndpoint.RoutePattern.RawText, out TemplateMatcher templateMatcher))
            {
                RouteTemplate template = TemplateParser.Parse(routeEndpoint.RoutePattern.RawText);
                templateMatcher = new TemplateMatcher(template, GetDefaultRouteValues(template));
                _templateMatcherCache.TryAdd(routeEndpoint.RoutePattern.RawText, templateMatcher);
            }

            routeValueDictionary = new RouteValueDictionary();
            if (templateMatcher.TryMatch(new PathString(requestInfo.RelativeUri), routeValueDictionary))
            {
                // Check if the HTTP method matches
                string requestHttpMethod = requestInfo.Method.ToLower();

                HttpMethodMetadata httpMethodMetadata = routeEndpoint.Metadata.GetMetadata <HttpMethodMetadata>();
                if (httpMethodMetadata == null && requestHttpMethod != HttpMethod.Get.ToString().ToLower())
                {                 // Assume get if no metadata is found
                    return(EndpointMatchResult.NoMatch);
                }
                if (!httpMethodMetadata.HttpMethods.Any(httpMethod => httpMethod.ToLower() == requestHttpMethod))
                {                 // Http method is not matching
                    return(EndpointMatchResult.NoMatch);
                }

                // Check if this endpoint is ignored, allowed takes precedence
                IgnoreForBatchRequestAttribute ignoreAttribute = routeEndpoint.Metadata.GetMetadata <IgnoreForBatchRequestAttribute>();
                AllowForBatchRequestAttribute  allowAttribute  = routeEndpoint.Metadata.GetMetadata <AllowForBatchRequestAttribute>();
                if (ignoreAttribute != null && allowAttribute == null)
                {
                    return(EndpointMatchResult.Ignored);
                }

                return(EndpointMatchResult.Match);
            }
            return(EndpointMatchResult.NoMatch);
        }
        public static IServiceCollection AddMediatREndpoints(this IServiceCollection services, IEnumerable <Type> handlerTypes)
        {
            var endpoints = new List <MediatorEndpoint>();

            foreach (var handlerType in handlerTypes)
            {
                var requestHandlerType = handlerType.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler <,>));
                if (requestHandlerType == null)
                {
                    throw new InvalidOperationException($"Type ({handlerType.FullName}) is not an IReqeustHandler<,>");
                }

                var requestArguments = requestHandlerType.GetGenericArguments();
                var requestType      = requestArguments[0];
                var responseType     = requestArguments[1];

                var requestMetadata = new MediatorEndpointMetadata(requestType, responseType);

                var attributes = handlerType.GetMethod("Handle").GetCustomAttributes(false);

                var httpAttributes = attributes.OfType <HttpMethodAttribute>().ToArray();
                if (httpAttributes.Length == 0)
                {
                    var httpMethodMetadata = new HttpMethodMetadata(new[] { HttpMethods.Post });

                    var metadata = new List <object>(attributes);
                    metadata.Add(httpMethodMetadata);
                    metadata.Add(requestMetadata);

                    endpoints.Add(new MediatorEndpoint
                    {
                        Metadata     = metadata,
                        HandlerType  = requestHandlerType,
                        RequestType  = requestMetadata.RequestType,
                        ResponseType = requestMetadata.ResponseType,
                        Uri          = requestMetadata.RequestType.Name
                    });
                }
                else
                {
                    for (var i = 0; i < httpAttributes.Length; i++)
                    {
                        var httpAttribute      = httpAttributes[i];
                        var httpMethodMetadata = new HttpMethodMetadata(httpAttribute.HttpMethods);

                        string template;
                        if (string.IsNullOrEmpty(httpAttribute.Template))
                        {
                            template = "/" + requestType.Name;
                        }
                        else
                        {
                            template = httpAttribute.Template;
                        }

                        var metadata = new List <object>(attributes);
                        metadata.Add(httpMethodMetadata);
                        metadata.Add(requestMetadata);

                        endpoints.Add(new MediatorEndpoint
                        {
                            Metadata     = metadata,
                            HandlerType  = requestHandlerType,
                            RequestType  = requestMetadata.RequestType,
                            ResponseType = requestMetadata.ResponseType,
                            Uri          = template
                        });
                    }
                }
            }

            services.Configure <MediatorEndpointOptions>(options =>
            {
                options.Endpoints = endpoints;
            });

            return(services);
        }