private IDictionary<string, object> GetParameterValuePairs(HttpActionDescriptor actionDescriptor)
        {
            IDictionary<string, object> parameterValuePairs = new Dictionary<string, object>();

            foreach (SwaggerDefaultValue defaultValue in actionDescriptor.GetCustomAttributes<SwaggerDefaultValue>())
            {
                parameterValuePairs.Add(defaultValue.Name, defaultValue.Value);
            }

            foreach (var parameter in actionDescriptor.GetParameters())
            {
                if (!parameter.ParameterType.IsPrimitive)
                {
                    foreach (PropertyInfo property in parameter.ParameterType.GetProperties())
                    {
                        var defaultValue = GetDefaultValue(property);

                        if (defaultValue != null)
                        {
                            parameterValuePairs.Add(property.Name, defaultValue);
                        }
                    }
                }
            }

            return parameterValuePairs;
        }
 private static bool HasQueryableAttribute(HttpActionDescriptor actionDescriptor)
 {
     #pragma warning disable 0618 // Disable obsolete warning for QueryableAttribute.
     return actionDescriptor.GetCustomAttributes<QueryableAttribute>(inherit: true).Any() ||
          actionDescriptor.ControllerDescriptor.GetCustomAttributes<QueryableAttribute>(inherit: true).Any();
     #pragma warning restore 0618
 }
Example #3
0
        private HttpActionDescriptor GetNewActionDescriptor(
            VersionNumber theRequestedApiVersion, 
            HttpActionDescriptor theOriginalHttpActionDescriptor)
        {
            var aApiVersionAttributes = theOriginalHttpActionDescriptor.GetCustomAttributes<ApiVersionAttribute>();
            if (aApiVersionAttributes == null || aApiVersionAttributes.Count == 0)
            {
                return theOriginalHttpActionDescriptor;
            }

            var aActionMappings = GetActionMapping(theOriginalHttpActionDescriptor.ControllerDescriptor);
            var aMatchedActionDescriptorMappings = new Dictionary<VersionNumber, HttpActionDescriptor>();
            foreach (var aApiVersionAttribute in aApiVersionAttributes)
            {
                var aActionName = aApiVersionAttribute.OperatioName;
                if (!aActionMappings.Contains(aActionName))
                {
                    continue;
                }

                var aHttpActionDescriptor = aActionMappings[aActionName].ElementAt(0);
                aMatchedActionDescriptorMappings[aApiVersionAttribute.VersionNumber] = aHttpActionDescriptor;
            }

            // this mapping could be cached
            if (aMatchedActionDescriptorMappings.Count == 0)
            {
                return theOriginalHttpActionDescriptor;
            }

            // customize version select logic here
            return CustomizedActionDescriptorSelector(theRequestedApiVersion, aMatchedActionDescriptorMappings);
        }
		/// <summary>
		/// Gets the documentation based on <see cref="T:System.Web.Http.Controllers.HttpActionDescriptor" />.
		/// </summary>
		/// <param name="actionDescriptor">The action descriptor.</param>
		/// <returns>The documentation for the action.</returns>
		public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
		{
			var methodNode = this.GetMethodNode(actionDescriptor);

			var s = new List<string>
						{
							GetTagValueForAction(methodNode, "summary"), 
							GetTagValueForAction(methodNode, "remarks")
						};

			// Add message if controller requires authorization
			if (actionDescriptor.GetCustomAttributes<AuthorizeAttribute>().Any())
			{
				s.Add("<p><i class='fa fa-lock'></i> Requires authorization!</p>");
			}

			// Add message if action is marked as Obsolete
			ObsoleteAttribute obsoleteAttribute = actionDescriptor.GetCustomAttributes<ObsoleteAttribute>().FirstOrDefault();
			if (obsoleteAttribute != null)
			{
				s.Add(string.Format("<p><i class='fa fa-warning'></i> This action is Obsolete: {0}</p>",
					string.IsNullOrEmpty(obsoleteAttribute.Message) ? "<i>unknown reason</i>" : obsoleteAttribute.Message));
			}

			return string.Join("", s.Where(x => !string.IsNullOrEmpty(x)));
		}
        public static WrapResultAttribute GetWrapResultAttributeOrNull(HttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null)
            {
                return null;
            }

            //Try to get for dynamic APIs (dynamic web api actions always define __OwDynamicApiDontWrapResultAttribute)
            var wrapAttr = actionDescriptor.Properties.GetOrDefault("__OwDynamicApiDontWrapResultAttribute") as WrapResultAttribute;
            if (wrapAttr != null)
            {
                return wrapAttr;
            }

            //Get for the action
            wrapAttr = actionDescriptor.GetCustomAttributes<WrapResultAttribute>().FirstOrDefault();
            if (wrapAttr != null)
            {
                return wrapAttr;
            }

            //Get for the controller
            wrapAttr = actionDescriptor.ControllerDescriptor.GetCustomAttributes<WrapResultAttribute>().FirstOrDefault();
            if (wrapAttr != null)
            {
                return wrapAttr;
            }

            //Not found
            return null;
        }
 protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
 {
     //Honor inherited route attributes, but only for the MicroCms.WebApi assembly.
     // To reduce conflicts and changing global behavior for apps that host MicroCms Web API
     if (IsCmsApiController(actionDescriptor.ControllerDescriptor.ControllerType))
         return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(true);
     return base.GetActionRouteFactories(actionDescriptor);
 }
        /// <summary>
        /// Returns an enumeration of filters.
        /// </summary>
        /// <param name="configuration">The HTTP configuration.</param>
        /// <param name="actionDescriptor">The action descriptor.</param>
        /// <returns>
        /// An enumeration of filters.
        /// </returns>
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor) {
            if (actionDescriptor == null ||
                (!IsIQueryable(actionDescriptor.ReturnType)) ||
                actionDescriptor.GetCustomAttributes<QueryableAttribute>().Any() ||
                actionDescriptor.GetParameters().Any(parameter => typeof (ODataQueryOptions).IsAssignableFrom(parameter.ParameterType)))
                return Enumerable.Empty<FilterInfo>();

            return new[] {new FilterInfo(_filter, FilterScope.Global)};
        }
        string IDocumentationProvider.GetDocumentation(HttpActionDescriptor actionDescriptor)
        {
            var actionDoc = actionDescriptor.GetCustomAttributes<ActionDocAttribute>().FirstOrDefault();
            if (actionDoc != null)
            {
                return actionDoc.Documentation;
            }

            return string.Format("Documentation for '{0}'.", actionDescriptor.ActionName);
        }
        public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
        {
            var apiDocumentation = actionDescriptor.GetCustomAttributes<ApiResponseDocumentationAttribute>().FirstOrDefault();
            if (apiDocumentation != null)
            {
                return apiDocumentation.Description;
            }

            return String.Empty;
        }
Example #10
0
 public string GetDocumentation(HttpActionDescriptor actionDescriptor)
 {
     string doc = "";
     var attr = actionDescriptor.GetCustomAttributes<ApiDocAttribute>().FirstOrDefault();
     if (attr != null)
     {
         doc = attr.Documentation;
     }
     return doc;
 }
        private static ODataActionDescriptor GetODataActionDescriptorFromAttributeRoute(HttpActionDescriptor actionDescriptor, ODataRoute oDataRoute, HttpConfiguration httpConfig)
        {
            Contract.Requires(actionDescriptor != null);
            Contract.Requires(oDataRoute != null);
            Contract.Ensures(Contract.Result<ODataActionDescriptor>() != null);

            var odataRouteAttribute = actionDescriptor.GetCustomAttributes<ODataRouteAttribute>()?.FirstOrDefault();
            Contract.Assume(odataRouteAttribute != null);
            var pathTemplate = HttpUtility.UrlDecode(oDataRoute.GetRoutePrefix().AppendPathSegment(odataRouteAttribute.PathTemplate));
            Contract.Assume(pathTemplate != null);
            return new ODataActionDescriptor(actionDescriptor, oDataRoute, pathTemplate, CreateHttpRequestMessage(actionDescriptor, oDataRoute, httpConfig));
        }
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null ||
              actionDescriptor.GetCustomAttributes<QueryableAttribute>().Any() || // if method already has a QueryableAttribute (or subclass) then skip it.
              actionDescriptor.GetParameters().Any(parameter => typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType))
            )
            {
                return Enumerable.Empty<FilterInfo>();
            }

            return new[] { new FilterInfo(_filter, FilterScope.Global) };
        }
Example #13
0
 protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
 {
     var fromBase = base.GetActionRouteFactories(actionDescriptor);
     System.Collections.ObjectModel.Collection<IDirectRouteFactory> newFactories = actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
     var combined = new List<IDirectRouteFactory>();
     if(fromBase != null)
     {
         combined.AddRange(fromBase);
     }
     if(newFactories != null)
     {
         combined.AddRange(newFactories);
     }
     return fromBase == null ? combined : fromBase;
 }
Example #14
0
        private bool DescriptionAuthorized(HttpActionContext actionContext, HttpActionDescriptor actionDescriptor) 
        {
     
            var attributes = actionDescriptor.GetCustomAttributes<Attribute>()
                 .ToArray();

            IEnumerable<ISwaggerAuthorization> swaggerAuthorization =
                attributes == null ? new List<ISwaggerAuthorization>() :
                                    attributes.Where(c => c as ISwaggerAuthorization != null).Cast<ISwaggerAuthorization>().ToList();

            foreach (var auth in swaggerAuthorization) {
                if (!auth.IsDescriptionAuthorized(actionContext)) {
                    return false;
                }
            }
            return true;
        }
        private HttpActionDescriptor CreateBetaAction(HttpActionDescriptor originalAction)
        {
            var attributes = originalAction.GetCustomAttributes<HasBetaTestingActionAttribute>().OfType<HasBetaTestingActionAttribute>();
            if (!attributes.Any())
            {
                return null;
            }

            var methodName = attributes.First().MethodName;
            var actionMethod = originalAction.ControllerDescriptor.ControllerType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
            if (actionMethod == null)
            {
                return null;
            }
           
            var actionDescriptor = new ReflectedHttpActionDescriptor(originalAction.ControllerDescriptor, actionMethod);
            actionDescriptor.Properties.TryAdd("IsBetaAction", true);
            return actionDescriptor;
        }
        protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(
            HttpActionDescriptor actionDescriptor)
        {
            var a = new List<RouteAttribute>();

            var ret = actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(true);

            foreach (var item in ret)
            {
                string routeprefix = null;

                var attribute = item as RouteAttribute;

                if (attribute == null) continue;

                var subRoute = attribute.Template;

                var method = actionDescriptor.SupportedHttpMethods[0].Method;

                var attribs = actionDescriptor.ControllerDescriptor.ControllerType.CustomAttributes.ToList();

                foreach (var attrib in attribs.Where(attrib => attrib.AttributeType == typeof(RoutePrefixAttribute)))
                    routeprefix = attrib.ConstructorArguments[0].Value.ToString();

                var key = routeprefix + "/" + subRoute;

                if (!Routes.ContainsKey(key))
                {
                    Routes.Add(key, new RouteInfo
                    {
                        Class = actionDescriptor.ControllerDescriptor.ControllerType.FullName,
                        Method = method
                    });
                }
                else
                {
                    Routes[key].Method += " " + method;
                }
            }

            return ret;
        }
        public IEnumerable<FilterInfo> GetFilters(
            HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            // Taken from ActionDescriptorFilterProvider
            var controllerFilters
                = GetFilterInfos(actionDescriptor.ControllerDescriptor.GetFilters(), FilterScope.Controller);
            var actionFilters
                = GetFilterInfos(actionDescriptor.GetFilters(), FilterScope.Action);
            // Taken from ActionDescriptorFilterProvider

            var controllerProxiedFilters
                = GetFilterInfos(actionDescriptor.ControllerDescriptor.GetCustomAttributes<IServiceAttribute>(),
                                 FilterScope.Controller);
            var actionProxiedFilters
                = GetFilterInfos(actionDescriptor.GetCustomAttributes<IServiceAttribute>(), FilterScope.Action);

            return controllerFilters
                .Concat(controllerProxiedFilters)
                .Concat(actionFilters)
                .Concat(actionProxiedFilters);
        }
        private IEnumerable<ODataPathTemplate> GetODataPathTemplates(string prefix, HttpActionDescriptor action)
        {
            Contract.Assert(action != null);

            IEnumerable<ODataRouteAttribute> routeAttributes = action.GetCustomAttributes<ODataRouteAttribute>(inherit: false);
            return
                routeAttributes
                .Select(route => GetODataPathTemplate(prefix, route.PathTemplate, action))
                .Where(template => template != null);
        }
        internal static Type GetElementType(HttpActionDescriptor actionDescriptor)
        {
            Type returnType = actionDescriptor.ReturnType;
            if (returnType == typeof(HttpResponseMessage) || typeof(IHttpActionResult).IsAssignableFrom(actionDescriptor.ReturnType))
            {
                ResponseTypeAttribute responseType = actionDescriptor.GetCustomAttributes<ResponseTypeAttribute>(inherit: true).FirstOrDefault();
                if (responseType != null)
                {
                    returnType = responseType.ResponseType;
                }
            }

            if (returnType != null)
            {
                return returnType.GetEnumerableElementType();
            }

            return null;
        }
        private ICorsPolicyProvider GetCorsPolicyProvider(HttpActionDescriptor actionDescriptor)
        {
            ICorsPolicyProvider policyProvider = null;
            if (actionDescriptor != null)
            {
                HttpControllerDescriptor controllerDescriptor = actionDescriptor.ControllerDescriptor;
                policyProvider = actionDescriptor.GetCustomAttributes<ICorsPolicyProvider>().FirstOrDefault();
                if (policyProvider == null && controllerDescriptor != null)
                {
                    policyProvider = controllerDescriptor.GetCustomAttributes<ICorsPolicyProvider>().FirstOrDefault();
                }
            }

            if (policyProvider == null)
            {
                policyProvider = DefaultPolicyProvider;
            }

            return policyProvider;
        }
        public string GetDocumentation(HttpActionDescriptor actionDescriptor)
        {
            var actionDescriptionAttributes = actionDescriptor.GetCustomAttributes<DescriptionAttribute>();

            return actionDescriptionAttributes.First().Description;
        }
Example #22
0
 GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
 {
     return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>
     (inherit: true);
 }
        /// <summary>
        /// Determines whether the action should be considered for <see cref="ApiExplorer.ApiDescriptions"/> generation. Called when initializing the <see cref="ApiExplorer.ApiDescriptions"/>.
        /// </summary>
        /// <param name="actionVariableValue">The action variable value from the route.</param>
        /// <param name="actionDescriptor">The action descriptor.</param>
        /// <param name="route">The route.</param>
        /// <returns><c>true</c> if the action should be considered for <see cref="ApiExplorer.ApiDescriptions"/> generation, <c>false</c> otherwise.</returns>
        public virtual bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)
        {
            if (actionDescriptor == null)
            {
                throw Error.ArgumentNull("actionDescriptor");
            }

            if (route == null)
            {
                throw Error.ArgumentNull("route");
            }

            ApiExplorerSettingsAttribute setting = actionDescriptor.GetCustomAttributes<ApiExplorerSettingsAttribute>().FirstOrDefault();
            NonActionAttribute nonAction = actionDescriptor.GetCustomAttributes<NonActionAttribute>().FirstOrDefault();
            return (setting == null || !setting.IgnoreApi) &&
                (nonAction == null) &&
                MatchRegexConstraint(route, ActionVariableName, actionVariableValue);
        }
 IEnumerable<SupraterraAuthorizeAttribute> GetApiAuthorizeAttributes(HttpActionDescriptor descriptor)
 {
     return descriptor.GetCustomAttributes<SupraterraAuthorizeAttribute>(true)
         .Concat(descriptor.ControllerDescriptor.GetCustomAttributes<SupraterraAuthorizeAttribute>(true));
 }
Example #25
0
 public string GetDocumentation(HttpActionDescriptor actionDescriptor)
 {
     var attr = actionDescriptor.GetCustomAttributes<ApiDocAttribute>().FirstOrDefault();
     return attr != null ? attr.Documentation : "";
 }
 private ResponseDescription CreateResponseDescription(HttpActionDescriptor actionDescriptor)
 {
     Type type = (
         from attribute in actionDescriptor.GetCustomAttributes<ResponseTypeAttribute>()
         select attribute.ResponseType).FirstOrDefault<Type>();
     ResponseDescription responseDescription = new ResponseDescription()
     {
         DeclaredType = actionDescriptor.ReturnType,
         ResponseType = type,
         Documentation = this.GetApiResponseDocumentation(actionDescriptor)
     };
     return responseDescription;
 }
        /// <summary>
        /// Gets a set of route factories for the given action descriptor.
        /// </summary>
        /// <param name="actionDescriptor">The action descriptor.</param>
        /// <returns>A set of route factories.</returns>
        /// <remarks>
        /// The implementation returns <see cref="IDirectRouteFactory"/> instances based on attributes on the action. Returns
        /// null if the action was defined on a base class of this controller.
        /// </remarks>
        protected virtual IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
        {
            // Ignore the Route attributes from inherited actions.
            ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
            if (reflectedActionDescriptor != null &&
                reflectedActionDescriptor.MethodInfo != null &&
                reflectedActionDescriptor.MethodInfo.DeclaringType != actionDescriptor.ControllerDescriptor.ControllerType)
            {
                return null;
            }

            Collection<IDirectRouteFactory> newFactories = actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: false);

            Collection<IHttpRouteInfoProvider> oldProviders = actionDescriptor.GetCustomAttributes<IHttpRouteInfoProvider>(inherit: false);

            List<IDirectRouteFactory> combined = new List<IDirectRouteFactory>();
            combined.AddRange(newFactories);

            foreach (IHttpRouteInfoProvider oldProvider in oldProviders)
            {
                if (oldProvider is IDirectRouteFactory)
                {
                    continue;
                }

                combined.Add(new RouteInfoDirectRouteFactory(oldProvider));
            }

            return combined;
        }
        private ResponseDescription CreateResponseDescription(HttpActionDescriptor actionDescriptor)
        {
            Collection<ResponseTypeAttribute> responseTypeAttribute = actionDescriptor.GetCustomAttributes<ResponseTypeAttribute>();
            Type responseType = responseTypeAttribute.Select(attribute => attribute.ResponseType).FirstOrDefault();

            return new ResponseDescription
            {
                DeclaredType = actionDescriptor.ReturnType,
                ResponseType = responseType,
                Documentation = GetApiResponseDocumentation(actionDescriptor)
            };
        }
Example #29
0
 /// <summary>
 /// Gets a set of route factories for the given action descriptor.
 /// </summary>
 /// <returns>
 /// A set of route factories.
 /// </returns>
 /// <param name="actionDescriptor">The action descriptor.</param>
 protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
 {
     // inherit route attributes decorated on base class controller's actions
     return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
 }
 protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
 {
     return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
 }