// Given an action, update the Controller Context's route data to use that action.
        // If you call action selection again after this method, it should still return the same result. 
        internal static void ElevateRouteData(this HttpControllerContext controllerContext, HttpActionDescriptor actionDescriptorSelected)
        {
            IHttpRouteData routeData = controllerContext.RouteData;

            IEnumerable<IHttpRouteData> multipleRouteData = routeData.GetSubRoutes();
            if (multipleRouteData == null)
            {
                return;
            }

            foreach (IHttpRouteData subData in multipleRouteData)
            {
                CandidateAction[] candidates = subData.Route.GetDirectRouteCandidates();

                if (candidates != null)
                {
                    foreach (CandidateAction candidate in candidates)
                    {
                        if (candidate.ActionDescriptor.Equals(actionDescriptorSelected))
                        {
                            controllerContext.RouteData = subData;
                            return;
                        }
                    }
                }
            }
        }
        public override IEdmModel GetModel(Type elementClrType, HttpRequestMessage request,
            HttpActionDescriptor actionDescriptor)
        {
            // Get model for the request
            IEdmModel model = request.ODataProperties().Model;

            if (model == null)
            {
                // user has not configured anything or has registered a model without the element type
                // let's create one just for this type and cache it in the action descriptor
                model = actionDescriptor.Properties.GetOrAdd("System.Web.OData.Model+" + elementClrType.FullName, _ =>
                {
                    ODataConventionModelBuilder builder =
                        new ODataConventionModelBuilder(actionDescriptor.Configuration, isQueryCompositionMode: true);
                    builder.EnableLowerCamelCase();
                    EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(elementClrType);
                    builder.AddEntitySet(elementClrType.Name, entityTypeConfiguration);
                    IEdmModel edmModel = builder.GetEdmModel();
                    Contract.Assert(edmModel != null);
                    return edmModel;
                }) as IEdmModel;
            }

            Contract.Assert(model != null);
            return model;
        }
 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
 }
        // Given an action, update the Controller Context's route data to use that action.
        // If you call action selection again after this method, it should still return the same result. 
        internal static void ElevateRouteData(this HttpControllerContext controllerContext, HttpActionDescriptor actionDescriptorSelected)
        {
            IHttpRouteData routeData = controllerContext.RouteData;

            IEnumerable<IHttpRouteData> multipleRouteData = routeData.GetSubRoutes();
            if (multipleRouteData == null)
            {
                return;
            }

            foreach (IHttpRouteData subData in multipleRouteData)
            {
                ReflectedHttpActionDescriptor[] actionDescriptors = subData.Route.GetDirectRouteActions();
                if (actionDescriptors != null)
                {
                    foreach (ReflectedHttpActionDescriptor ad in actionDescriptors)
                    {
                        if (ad.Equals(actionDescriptorSelected))
                        {
                            controllerContext.RouteData = subData;
                            return;
                        }
                    }
                }
            }
        }
        private static HttpRequestMessage CreateHttpRequestMessage(HttpActionDescriptor actionDescriptor, ODataRoute oDataRoute, HttpConfiguration httpConfig)
        {
            Contract.Requires(httpConfig != null);
            Contract.Requires(oDataRoute != null);
            Contract.Requires(httpConfig != null);
            Contract.Ensures(Contract.Result<HttpRequestMessage>() != null);

            Contract.Assume(oDataRoute.Constraints != null);

            var httpRequestMessage = new HttpRequestMessage(actionDescriptor.SupportedHttpMethods.First(), "http://any/");

            var requestContext = new HttpRequestContext
            {
                Configuration = httpConfig
            };
            httpRequestMessage.SetConfiguration(httpConfig);
            httpRequestMessage.SetRequestContext(requestContext);

            var httpRequestMessageProperties = httpRequestMessage.ODataProperties();
            Contract.Assume(httpRequestMessageProperties != null);
            httpRequestMessageProperties.Model = oDataRoute.GetEdmModel();
            httpRequestMessageProperties.RouteName = oDataRoute.GetODataPathRouteConstraint().RouteName;
            httpRequestMessageProperties.RoutingConventions = oDataRoute.GetODataPathRouteConstraint().RoutingConventions;
            httpRequestMessageProperties.PathHandler = oDataRoute.GetODataPathRouteConstraint().PathHandler;
            return httpRequestMessage;
        }
        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;
        }
Example #7
0
 public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null)
 {
     HttpControllerContext context = controllerContext ?? CreateControllerContext();
     HttpActionDescriptor descriptor = actionDescriptor ?? CreateActionDescriptor();
     descriptor.ControllerDescriptor = context.ControllerDescriptor;
     return new HttpActionContext(context, descriptor);
 }
        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;
        }
        private Member GetMember(HttpActionDescriptor actionDescriptor)
        {
            var reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
            if (reflectedActionDescriptor == null)
                return new Member();


            var xMember = _xMembers.Elements().FirstOrDefault(x => x.Attribute("name").Value == "M:" + GetMemberName(reflectedActionDescriptor.MethodInfo));
            if (xMember == null)
                return new Member();

            var xSummary = xMember.Element("summary");
            var xRemarks = xMember.Element("remarks");

            return new Member()
            {
                Summary = xSummary != null ? xSummary.Value : null,
                Remarks = xRemarks != null ? xRemarks.Value : null,
                Parameters = xMember.Elements("param").Select(p => new XParameter()
                {
                    Name = p.Attribute("name").Value,
                    Value = p.Value
                })
            };
        }
		/// <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)));
		}
        private static async Task<HttpResponseMessage> InvokeUsingActionResultAsync(HttpActionContext actionContext,
            HttpActionDescriptor actionDescriptor, CancellationToken cancellationToken)
        {
            Contract.Assert(actionContext != null);

            HttpControllerContext controllerContext = actionContext.ControllerContext;

            object result = await actionDescriptor.ExecuteAsync(controllerContext, actionContext.ActionArguments,
                cancellationToken);

            if (result == null)
            {
                throw new InvalidOperationException(SRResources.ApiControllerActionInvoker_NullHttpActionResult);
            }

            IHttpActionResult actionResult = result as IHttpActionResult;

            if (actionResult == null)
            {
                throw new InvalidOperationException(Error.Format(
                    SRResources.ApiControllerActionInvoker_InvalidHttpActionResult, result.GetType().Name));
            }

            HttpResponseMessage response = await actionResult.ExecuteAsync(cancellationToken);

            if (response == null)
            {
                throw new InvalidOperationException(
                    SRResources.ResponseMessageResultConverter_NullHttpResponseMessage);
            }

            response.EnsureResponseHasRequest(actionContext.Request);

            return response;
        }
        public string GetDocumentation(HttpActionDescriptor actionDescriptor)
        {
            XPathNavigator memberNode = GetMemberNode(actionDescriptor);

            if (memberNode != null)
            {
                XPathNavigator summaryNode = memberNode.SelectSingleNode("summary");
                XPathNavigator jsonNode = memberNode.SelectSingleNode("jsonResponse");

                if (summaryNode != null)
                {
                    var docDescription = new StringBuilder();

                    docDescription.Append(summaryNode.Value.Trim().Replace("[br]", "<br/>"));

                    if (jsonNode != null)
                    {
                        docDescription.AppendLine("<div class='json' style='display: none;'>");
                        docDescription.Append(jsonNode.Value.Trim());
                        docDescription.AppendLine("</div>");

                        docDescription.AppendLine("<pre>");
                        docDescription.AppendLine("</pre>");

                    }

                    return docDescription.ToString();
                }

            }

            return string.Empty;
        }
 public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
 {
     var httpParameterDescriptors = actionDescriptor.GetParameters();
     Contract.Assume(httpParameterDescriptors != null);
     return httpParameterDescriptors
         .SingleOrDefault(descriptor => string.Equals(descriptor.ParameterName, swaggerParameter.name, StringComparison.CurrentCultureIgnoreCase));
 }
 public HttpParameterDescriptor Map(Parameter swaggerParameter, int parameterIndex, HttpActionDescriptor actionDescriptor)
 {
     // Maybe the parameter is a key parameter, e.g., where Id in the URI path maps to a parameter named 'key'
     if (swaggerParameter.description != null && swaggerParameter.description.StartsWith("key:"))
     {
         // Find either a single 'key' in the route or composite keys
         // which take the form of key<parameter name>
         var keyParameterName = swaggerParameter
                                 .description
                                 .Replace(FindKeyReplacementSubStr, 
                                             String.Empty)
                                 .ToLower();
         var parameterDescriptor = 
             actionDescriptor
                 .GetParameters()?
                 .SingleOrDefault(descriptor =>
                     descriptor.ParameterName.ToLower() == KeyName
                     || descriptor.ParameterName.ToLower().Equals(keyParameterName)
                 );
         if (parameterDescriptor != null && !parameterDescriptor.IsODataLibraryType())
         {
             var httpControllerDescriptor = actionDescriptor.ControllerDescriptor;
             Contract.Assume(httpControllerDescriptor != null);
             return new ODataParameterDescriptor(swaggerParameter.name, parameterDescriptor.ParameterType, parameterDescriptor.IsOptional, parameterDescriptor)
             {
                 Configuration = httpControllerDescriptor.Configuration,
                 ActionDescriptor = actionDescriptor,
                 ParameterBinderAttribute = parameterDescriptor.ParameterBinderAttribute
             };
         }
     }
     return null;
 }
		internal static bool ActionHasChangeSetEntityParameter(HttpActionDescriptor actionDescriptor)
		{
			Contract.Assert(actionDescriptor != null);

			var parameters = actionDescriptor.GetParameters();
			return (parameters.Count > 0) && IsChangeSetEntityParameter(parameters[0]);
		}
 /// <summary>
 /// Gets the action's response documentation based on <see cref="System.Web.Http.Controllers.HttpActionDescriptor"/>.
 /// </summary>
 /// <param name="actionDescriptor">The action descriptor.</param>
 /// <returns>The documentation for the controller.</returns>
 public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
 {
     return this.sources
         .Select(source => source.GetResponseDocumentation(actionDescriptor))
         .Where(documentation => !string.IsNullOrEmpty(documentation))
         .FirstOrDefault();
 }
Example #17
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);
        }
        private IList<ApiParameterDescription> CreateParameterDescription(HttpActionBinding actionBinding,HttpActionDescriptor actionDescriptor)
        {
            IList<ApiParameterDescription> parameterDescriptions = new List<ApiParameterDescription>();
            // try get parameter binding information if available
            if (actionBinding != null)
            {
                HttpParameterBinding[] parameterBindings = actionBinding.ParameterBindings;
                if (parameterBindings != null)
                {
                    foreach (HttpParameterBinding parameter in parameterBindings)
                    {
                        parameterDescriptions.Add(CreateParameterDescriptionFromBinding(parameter));
                    }
                }
            }
            else
            {
                Collection<HttpParameterDescriptor> parameters = actionDescriptor.GetParameters();
                if (parameters != null)
                {
                    foreach (HttpParameterDescriptor parameter in parameters)
                    {
                        parameterDescriptions.Add(CreateParameterDescriptionFromDescriptor(parameter));
                    }
                }
            }

            return parameterDescriptions;
        }
 public static string Name(HttpActionDescriptor actionDescriptor)
 {
     return string.Format(Format,
         actionDescriptor.ControllerDescriptor.ControllerType.FullName,
         actionDescriptor.ActionName,
         ParameterDescriptions(actionDescriptor));
 }
 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);
 }
Example #21
0
        internal static HttpActionContext CreateActionContext(
            HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null, HttpRequestMessage request = null) {

            HttpControllerContext controllerCtx = controllerContext ?? CreateControllerContext(request: request);
            HttpActionDescriptor descriptor = actionDescriptor ?? new Mock<HttpActionDescriptor>() { CallBase = true }.Object;

            return new HttpActionContext(controllerCtx, descriptor);
        }
 public void InitializesInnerActionDescriptorCorrectly(HttpActionDescriptor innerDescriptor,
     IActionResultConverter converter)
 {
     // Exercise system
     var descriptor = new DelegatingActionDescriptor(innerDescriptor, converter);
     // Verify outcome
     descriptor.InnerActionDescriptor.Should().Be(innerDescriptor);
 }
        private static string GetApiDocumentation(HttpActionDescriptor actionDescriptor)
        {
            Contract.Requires(actionDescriptor != null);
            Contract.Requires(actionDescriptor.Configuration != null);

            var documentationProvider = actionDescriptor.Configuration.Services.GetDocumentationProvider();
            return documentationProvider?.GetDocumentation(actionDescriptor);
        }
        /// <summary>Initializes a new instance of <see cref="DelegatingActionDescriptor"/>.</summary>
        /// <param name="descriptor">The descriptor to which to delegate member invocations.</param>
        /// <param name="resultConverter">The custom converter.</param>
        public DelegatingActionDescriptor(HttpActionDescriptor descriptor, IActionResultConverter resultConverter)
        {
            if (descriptor == null) throw new ArgumentNullException(nameof(descriptor));
            if (resultConverter == null) throw new ArgumentNullException(nameof(resultConverter));

            InnerActionDescriptor = descriptor;
            ResultConverter = resultConverter;
        }
 public virtual void LogAction(HttpActionDescriptor actionDescriptor, string prefix)
 {
     _logger.DebugFormat(
         LogTextFormatString,
         prefix,
         actionDescriptor.ControllerDescriptor.ControllerName,
         actionDescriptor.ActionName);
 }
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor.ControllerDescriptor.ControllerType == typeof(OpenPermitController))
            {
                return new List<FilterInfo> { new FilterInfo(this, FilterScope.Action) };
            }

            return new List<FilterInfo>();
        }
 private static string ParameterDescriptions(HttpActionDescriptor actionDescripton)
 {
     var description = new StringBuilder();
     foreach (var parameter in actionDescripton.GetParameters())
     {
         description.AppendFormat("{0}:{1}/", parameter.ParameterType, parameter.ParameterName);
     }
     return description.ToString();
 }
        /// <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)};
        }
        public void CreateBuilderWithoutResolverAndBuild_SetsActionsDataToken()
        {
            var actions = new HttpActionDescriptor[] { new ReflectedHttpActionDescriptor() };

            var route = BuildWithoutResolver("route", actions);

            var actualActions = route.DataTokens[RouteDataTokenKeys.Actions];
            Assert.Equal(actions, actualActions);
        }
        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            return configuration.Filters;
        }