static bool IsDecoratedWithAttributes(HttpControllerDescriptor controller) { Contract.Requires(controller != null); return(controller.GetCustomAttributes <IApiVersionProvider>().Count > 0 || controller.GetCustomAttributes <IApiVersionNeutral>().Count > 0); }
/// <summary> /// Gets route factories for the given controller descriptor. /// </summary> /// <param name="controllerDescriptor">The controller descriptor.</param> /// <returns>A set of route factories.</returns> /// <remarks> /// The implementation returns <see cref="IDirectRouteFactory"/> instances based on attributes on the controller. /// </remarks> protected virtual IReadOnlyList <IDirectRouteFactory> GetControllerRouteFactories( HttpControllerDescriptor controllerDescriptor ) { Collection <IDirectRouteFactory> newFactories = controllerDescriptor.GetCustomAttributes <IDirectRouteFactory>(inherit: false); Collection <IHttpRouteInfoProvider> oldProviders = controllerDescriptor.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 static IReadOnlyCollection <IDirectRouteProvider> GetRouteProviders( HttpControllerDescriptor controller) { Collection <IDirectRouteProvider> newProviders = controller.GetCustomAttributes <IDirectRouteProvider>(inherit: false); Collection <IHttpRouteInfoProvider> oldProviders = controller.GetCustomAttributes <IHttpRouteInfoProvider>(inherit: false); List <IDirectRouteProvider> combined = new List <IDirectRouteProvider>(); combined.AddRange(newProviders); foreach (IHttpRouteInfoProvider oldProvider in oldProviders) { if (oldProvider is IDirectRouteProvider) { continue; } combined.Add(new RouteInfoDirectRouteProvider(oldProvider)); } return(combined); }
public StateHolder(IControllerConventionBuilder controller, HttpControllerDescriptor descriptor) { Controller = controller; ControllerDescriptor = descriptor; // apply lazy loading to properties so that they are loaded and cached when needed // instead of right a way. _controllerIntroduced = new Lazy <IntroducedInApiVersionAttribute>( () => ControllerDescriptor.GetCustomAttributes <IntroducedInApiVersionAttribute>().SingleOrDefault()); _controllerRemoved = new Lazy <RemovedInApiVersionAttribute>( () => ControllerDescriptor.GetCustomAttributes <RemovedInApiVersionAttribute>().SingleOrDefault()); _actionDescriptors = new Lazy <HttpActionDescriptor[]>( () => new ApiControllerActionSelector().GetActionMapping(descriptor)?.SelectMany(x => x).ToArray() ?? Array.Empty <HttpActionDescriptor>()); }
private static string GetRoutePrefix(HttpControllerDescriptor controller) { Collection <RoutePrefixAttribute> attributes = controller.GetCustomAttributes <RoutePrefixAttribute>(inherit: false); if (attributes.Count > 0) { RoutePrefixAttribute attribute = attributes[0]; if (attribute != null) { string prefix = attribute.Prefix; if (prefix != null) { if (prefix.EndsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation(SRResources.AttributeRoutes_InvalidPrefix, prefix, controller.ControllerName); } return(prefix); } } } return(null); }
/// <summary> /// Applies a controller convention given the specified builder and model. /// </summary> /// <param name="controller">The <see cref="IControllerConventionBuilder">builder</see> used to apply conventions.</param> /// <param name="controllerDescriptor">The <see cref="HttpControllerDescriptor">descriptor</see> to build conventions from.</param> /// <returns>True if any conventions were applied to the <paramref name="controllerDescriptor">descriptor</paramref>; /// otherwise, false.</returns> public virtual bool Apply(IControllerConventionBuilder controller, HttpControllerDescriptor controllerDescriptor) { Arg.NotNull(controller, nameof(controller)); Arg.NotNull(controllerDescriptor, nameof(controller)); var text = GetRawApiVersion(controllerDescriptor.ControllerType.Namespace); if (!ApiVersion.TryParse(text, out var apiVersion)) { return(false); } var deprecated = controllerDescriptor.GetCustomAttributes <ObsoleteAttribute>().Any(); if (deprecated) { controller.HasDeprecatedApiVersion(apiVersion); } else { controller.HasApiVersion(apiVersion); } return(true); }
static IEnumerable <string> GetODataRoutePrefixes(HttpControllerDescriptor controllerDescriptor) { Contract.Assert(controllerDescriptor != null); Contract.Ensures(Contract.Result <IEnumerable <string> >() != null); var prefixAttributes = controllerDescriptor.GetCustomAttributes <ODataRoutePrefixAttribute>(inherit: false); if (prefixAttributes.Count == 0) { yield return(null); } else { foreach (var prefixAttribute in prefixAttributes) { var prefix = prefixAttribute.Prefix; if (prefix != null && prefix.StartsWith("/", StringComparison.Ordinal)) { throw new InvalidOperationException(SR.RoutePrefixStartsWithSlash.FormatDefault(prefix, controllerDescriptor.ControllerType.FullName)); } if (prefix != null && prefix.EndsWith("/", StringComparison.Ordinal)) { prefix = prefix.TrimEnd('/'); } yield return(prefix); } } }
protected override IReadOnlyList <IDirectRouteFactory> GetControllerRouteFactories(HttpControllerDescriptor controllerDescriptor) { // Inherit route attributes decorated on base class controller // GOTCHA: RoutePrefixAttribute doesn't show up here, even though we were expecting it to. // Am keeping this here anyways, but am implementing an ugly fix by overriding GetRoutePrefix return(controllerDescriptor.GetCustomAttributes <IDirectRouteFactory>(inherit: true)); }
public override bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route) { if (controllerDescriptor == null) { throw new ArgumentNullException("controllerDescriptor"); } if (route == null) { throw new ArgumentNullException("route"); } ApiExplorerSettingsAttribute setting = controllerDescriptor.GetCustomAttributes <ApiExplorerSettingsAttribute>().FirstOrDefault(); string hcNamespace = string.Empty; string routetemplate = string.Empty; routetemplate = route.RouteTemplate.Split('/')[1]; hcNamespace = controllerDescriptor.ControllerType.Namespace; if (hcNamespace.Contains(routetemplate)) { return((setting == null || !setting.IgnoreApi) && MatchRegexConstraint(route, "controller", controllerVariableValue)); } else { return(false); } }
private static IEnumerable <string> GetODataRoutePrefixes(HttpControllerDescriptor controllerDescriptor) { Contract.Assert(controllerDescriptor != null); var prefixAttributes = controllerDescriptor.GetCustomAttributes <ODataRoutePrefixAttribute>(inherit: false); if (prefixAttributes.Count == 0) { yield return(null); } else { foreach (ODataRoutePrefixAttribute prefixAttribute in prefixAttributes) { string prefix = prefixAttribute.Prefix; if (prefix != null && prefix.StartsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation(SRResources.RoutePrefixStartsWithSlash, prefix, controllerDescriptor.ControllerType.FullName); } if (prefix != null && prefix.EndsWith("/", StringComparison.Ordinal)) { prefix = prefix.TrimEnd('/'); } yield return(prefix); } } }
/// <summary> /// Determines whether the controller should be considered. /// </summary> /// <param name="controllerRouteParameterValue">The controller route parameter value.</param> /// <param name="controllerDescriptor">The associated <see cref="HttpControllerDescriptor">controller descriptor</see>.</param> /// <param name="route">The associated <see cref="IHttpRoute">route</see>.</param> /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> to consider the controller for.</param> /// <returns>True if the controller should be explored; otherwise, false.</returns> protected override bool ShouldExploreController(string controllerRouteParameterValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route, ApiVersion apiVersion) { Arg.NotNull(controllerDescriptor, nameof(controllerDescriptor)); Arg.NotNull(route, nameof(route)); Arg.NotNull(apiVersion, nameof(apiVersion)); if (typeof(MetadataController).IsAssignableFrom(controllerDescriptor.ControllerType)) { return(false); } var routeTemplate = route.RouteTemplate; if (!odataVariableRegex.IsMatch(routeTemplate)) { return(base.ShouldExploreController(controllerRouteParameterValue, controllerDescriptor, route, apiVersion)); } if (UseApiExplorerSettings) { var setting = controllerDescriptor.GetCustomAttributes <ApiExplorerSettingsAttribute>().FirstOrDefault(); if (setting?.IgnoreApi == true) { return(false); } } return(controllerDescriptor.GetDeclaredApiVersions().Contains(apiVersion)); }
private void MergeAttributesWithConventions(HttpControllerDescriptor controllerDescriptor) { Contract.Requires(controllerDescriptor != null); if (VersionNeutral) { return; } var providers = controllerDescriptor.GetCustomAttributes <IApiVersionProvider>().ToArray(); supportedVersions.UnionWith(from provider in providers where !provider.AdvertiseOnly && !provider.Deprecated from version in provider.Versions select version); deprecatedVersions.UnionWith(from provider in providers where !provider.AdvertiseOnly && provider.Deprecated from version in provider.Versions select version); advertisedVersions.UnionWith(from provider in providers where provider.AdvertiseOnly && !provider.Deprecated from version in provider.Versions select version); deprecatedAdvertisedVersions.UnionWith(from provider in providers where provider.AdvertiseOnly && provider.Deprecated from version in provider.Versions select version); }
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); }
/// <summary> /// Applies a controller convention given the specified builder and model. /// </summary> /// <param name="controller">The <see cref="IControllerConventionBuilder">builder</see> used to apply conventions.</param> /// <param name="controllerDescriptor">The <see cref="HttpControllerDescriptor">descriptor</see> to build conventions from.</param> /// <returns>True if any conventions were applied to the <paramref name="controllerDescriptor">descriptor</paramref>; /// otherwise, false.</returns> public virtual bool Apply(IControllerConventionBuilder controller, HttpControllerDescriptor controllerDescriptor) { if (controller == null) { throw new ArgumentNullException(nameof(controller)); } if (controllerDescriptor == null) { throw new ArgumentNullException(nameof(controllerDescriptor)); } if (GetApiVersion(controllerDescriptor.ControllerType.Namespace) is not ApiVersion apiVersion) { return(false); } var deprecated = controllerDescriptor.GetCustomAttributes <ObsoleteAttribute>().Any(); if (deprecated) { controller.HasDeprecatedApiVersion(apiVersion); } else { controller.HasApiVersion(apiVersion); } return(true); }
/// <remarks>This signature uses types that are AspNet-specific.</remarks> private static IEnumerable <string> GetODataRoutePrefixes(HttpControllerDescriptor controllerDescriptor) { Contract.Assert(controllerDescriptor != null); var prefixAttributes = controllerDescriptor.GetCustomAttributes <ODataRoutePrefixAttribute>(inherit: false); return(GetODataRoutePrefixes(prefixAttributes, controllerDescriptor.ControllerType.FullName)); }
public static bool IsAttributeDefined <TAttribute>(this HttpControllerDescriptor controllerDesc, bool inherit = false) where TAttribute : Attribute { var attribs = controllerDesc.GetCustomAttributes <TAttribute>(inherit); var ret = attribs.HasAny(); return(ret); }
public override bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route) { var hpidAttribute = controllerDescriptor.GetCustomAttributes <HPIDEnableAttribute>().FirstOrDefault(); if (hpidAttribute != null) { return(SettingRepository.Get <bool>("HPIDEnabled", true)); } var swaggerAttribute = controllerDescriptor.GetCustomAttributes <SwaggerEnableAttribute>().FirstOrDefault(); if (swaggerAttribute != null) { return(NewRESTApi); } return(true); }
private AccessControlAttribute GetControllerAttribute(HttpControllerDescriptor controllerDescriptor) { var result = controllerDescriptor .GetCustomAttributes <AccessControlAttribute>(true) .SingleOrDefault(); return(result); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { //得到描述目标Action的HttpActionDescriptor HttpMethod originalMethod = request.Method; bool isPreflightRequest = request.IsPreflightRequest(); if (isPreflightRequest) { string method = request.Headers.GetValues("Access-Control-Request-Method").First(); request.Method = new HttpMethod(method); } HttpConfiguration configuration = request.GetConfiguration(); HttpControllerDescriptor controllerDescriptor = configuration.Services.GetHttpControllerSelector().SelectController(request); HttpControllerContext controllerContext = new HttpControllerContext(request.GetConfiguration(), request.GetRouteData(), request) { ControllerDescriptor = controllerDescriptor }; HttpActionDescriptor actionDescriptor = configuration.Services.GetActionSelector().SelectAction(controllerContext); //根据HttpActionDescriptor得到应用的CorsAttribute特性 CorsAttribute corsAttribute = actionDescriptor.GetCustomAttributes <CorsAttribute>().FirstOrDefault() ?? controllerDescriptor.GetCustomAttributes <CorsAttribute>().FirstOrDefault(); if (null == corsAttribute) { return(base.SendAsync(request, cancellationToken)); } //利用CorsAttribute实施授权并生成响应报头 IDictionary <string, string> headers; request.Method = originalMethod; bool authorized = corsAttribute.TryEvaluate(request, out headers); HttpResponseMessage response; if (isPreflightRequest) { if (authorized) { response = new HttpResponseMessage(HttpStatusCode.OK); } else { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, corsAttribute.ErrorMessage); } } else { response = base.SendAsync(request, cancellationToken).Result; } //添加响应报头 foreach (var item in headers) { response.Headers.Add(item.Key, item.Value); } return(Task.FromResult <HttpResponseMessage>(response)); }
public void GetCustomAttributesInheritFalse_GetsDeclaredAttributes() { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor desc = new HttpControllerDescriptor(config, "MyController", typeof(MyDerived1Controller)); var attributes = desc.GetCustomAttributes <MyConfigDerived1Attribute>(inherit: false); Assert.Equal(1, attributes.Count); }
public void GetCustomAttributesInheritFalse_DoesNotGetInheritedAttributes() { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor desc = new HttpControllerDescriptor(config, "MyController", typeof(MyDerived1Controller)); var attributes = desc.GetCustomAttributes <MyConfigBaseAttribute>(inherit: false); Assert.Empty(attributes); }
public void GetCustomAttributesInheritTrue_GetsInheritedAttributes() { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor desc = new HttpControllerDescriptor(config, "MyController", typeof(MyDerived1Controller)); var attributes = desc.GetCustomAttributes <MyConfigBaseAttribute>(inherit: true); Assert.Single(attributes); }
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { string doc = ""; var attr = controllerDescriptor.GetCustomAttributes<ApiControllerDocAttribute>().FirstOrDefault(); if (attr != null) { doc = attr.Documentation; } return doc; }
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { var apiDocumentation = controllerDescriptor.GetCustomAttributes<ApiDocumentationAttribute>().FirstOrDefault(); if (apiDocumentation != null) { return apiDocumentation.Description; } return String.Empty; }
/// <summary> /// Initializes a new instance of the <see cref="ApiVersionModel"/> class. /// </summary> /// <param name="controllerDescriptor">The <see cref="HttpControllerDescriptor"/> to initialize the API version model from.</param> public ApiVersionModel(HttpControllerDescriptor controllerDescriptor) { Arg.NotNull(controllerDescriptor, nameof(controllerDescriptor)); if (IsApiVersionNeutral = controllerDescriptor.GetCustomAttributes <IApiVersionNeutral>(false).Any()) { declaredVersions = emptyVersions; implementedVersions = emptyVersions; supportedVersions = emptyVersions; deprecatedVersions = emptyVersions; } else { declaredVersions = new Lazy <IReadOnlyList <ApiVersion> >(() => GetDeclaredControllerApiVersions(controllerDescriptor)); implementedVersions = declaredVersions; supportedVersions = new Lazy <IReadOnlyList <ApiVersion> >(() => GetSupportedControllerApiVersions(controllerDescriptor)); deprecatedVersions = new Lazy <IReadOnlyList <ApiVersion> >(controllerDescriptor.GetCustomAttributes <IApiVersionProvider>(false).GetDeprecatedApiVersions); } }
private static IEnumerable <HttpRouteEntry> CreateRouteEntries(HttpControllerDescriptor controllerDescriptor) { IHttpActionSelector actionSelector = controllerDescriptor.Configuration.Services.GetActionSelector(); ILookup <string, HttpActionDescriptor> actionMap = actionSelector.GetActionMapping(controllerDescriptor); if (actionMap == null) { return(Enumerable.Empty <HttpRouteEntry>()); } List <HttpRouteEntry> routes = new List <HttpRouteEntry>(); string routePrefix = GetRoutePrefix(controllerDescriptor); List <ReflectedHttpActionDescriptor> actionsWithoutRoutes = new List <ReflectedHttpActionDescriptor>(); foreach (IGrouping <string, HttpActionDescriptor> actionGrouping in actionMap) { string actionName = actionGrouping.Key; foreach (ReflectedHttpActionDescriptor actionDescriptor in actionGrouping.OfType <ReflectedHttpActionDescriptor>()) { Collection <IHttpRouteInfoProvider> routeProviders = actionDescriptor.GetCustomAttributes <IHttpRouteInfoProvider>(inherit: false); // Ignore the Route attributes from inherited actions. if (actionDescriptor.MethodInfo != null && actionDescriptor.MethodInfo.DeclaringType != controllerDescriptor.ControllerType) { routeProviders = null; } if (routeProviders != null && routeProviders.Count > 0) { AddRouteEntries(routes, actionName, routePrefix, routeProviders, new ReflectedHttpActionDescriptor[] { actionDescriptor }); } else { // IF there are no routes on the specific action, attach it to the controller routes (if any). actionsWithoutRoutes.Add(actionDescriptor); } } } Collection <IHttpRouteInfoProvider> controllerRouteProviders = controllerDescriptor.GetCustomAttributes <IHttpRouteInfoProvider>(inherit: false); // If they exist and have not been overridden, create routes for controller-level route providers. if (controllerRouteProviders != null && controllerRouteProviders.Count > 0 && actionsWithoutRoutes.Count > 0) { AddRouteEntries(routes, actionsWithoutRoutes[0].ActionName, routePrefix, controllerRouteProviders, actionsWithoutRoutes); } return(routes); }
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { var apiDocumentation = controllerDescriptor.GetCustomAttributes <ApiDocumentationAttribute>().FirstOrDefault(); if (apiDocumentation != null) { return(apiDocumentation.Description); } return(String.Empty); }
private static bool SkipAuthorization(HttpActionContext actionContext) { if (actionContext == null) { return(false); } HttpActionDescriptor actionDesc = actionContext.ActionDescriptor; HttpControllerDescriptor controllerDesc = actionContext.ControllerContext.ControllerDescriptor; return(actionDesc.GetCustomAttributes <AllowAnonymousAttribute>().Any() || controllerDesc.GetCustomAttributes <AllowAnonymousAttribute>().Any()); }
public HttpActionContextBuilder() { var attributes = new Collection <AllowAnonymousAttribute>(); _controllerDescriptor = Substitute.For <HttpControllerDescriptor>(); _controllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Returns(attributes); _actionDescriptor = Substitute.For <HttpActionDescriptor>(); _actionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>() .Returns(attributes); _requestSubstitute = new HttpRequestMessage(); }
/// <summary> /// Gets the route prefix from the provided controller. /// </summary> /// <param name="controllerDescriptor">The controller descriptor.</param> /// <returns>The route prefix or null.</returns> protected virtual string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor) { Collection <IRoutePrefix> attributes = controllerDescriptor.GetCustomAttributes <IRoutePrefix>(inherit: false); if (attributes == null) { return(null); } if (attributes.Count > 1) { string errorMessage = Error.Format( SRResources.RoutePrefix_CannotSupportMultiRoutePrefix, controllerDescriptor.ControllerType.FullName ); throw new InvalidOperationException(errorMessage); } if (attributes.Count == 1) { IRoutePrefix attribute = attributes[0]; if (attribute != null) { string prefix = attribute.Prefix; if (prefix == null) { string errorMessage = Error.Format( SRResources.RoutePrefix_PrefixCannotBeNull, controllerDescriptor.ControllerType.FullName ); throw new InvalidOperationException(errorMessage); } if (prefix.EndsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation( SRResources.AttributeRoutes_InvalidPrefix, prefix, controllerDescriptor.ControllerName ); } return(prefix); } } return(null); }
private static IReadOnlyList <ApiVersion> GetDeclaredControllerApiVersions(HttpControllerDescriptor controllerDescriptor) { Contract.Requires(controllerDescriptor != null); Contract.Ensures(Contract.Result <IReadOnlyList <ApiVersion> >() != null); var versions = controllerDescriptor.GetCustomAttributes <IApiVersionProvider>(false).GetImplementedApiVersions(); if (versions.Count == 0) { versions = new[] { controllerDescriptor.Configuration.GetApiVersioningOptions().DefaultApiVersion }; } return(versions); }
protected override string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor) { var routePrefix = base.GetRoutePrefix(controllerDescriptor); var autoRoutePrefixAttribute = controllerDescriptor.GetCustomAttributes <AutoRoutePrefixAttribute>(inherit: true).FirstOrDefault(); if (autoRoutePrefixAttribute != null) { var autoRoutePrefix = string.Empty; var namespacePath = controllerDescriptor.ControllerType.Namespace.Replace(ControllersNamespace, ""); if (namespacePath.Length > 0) { autoRoutePrefix = string.Join("/", namespacePath .Substring(1) .Split(new char[] { '.' }, StringSplitOptions.None) .Select(x => x.ToCamelCase())); } if (!autoRoutePrefixAttribute.ExcludeControllerName) { var controllerName = controllerDescriptor.ControllerName.ToCamelCase(); if (string.IsNullOrEmpty(autoRoutePrefix)) { autoRoutePrefix = controllerName; } else { autoRoutePrefix += "/" + controllerName; } } if (string.IsNullOrEmpty(routePrefix) || autoRoutePrefixAttribute.Mode == AutoRoutePrefixMode.ReplaceDefaultPrefix) { routePrefix = autoRoutePrefix; } else if (autoRoutePrefixAttribute.Mode == AutoRoutePrefixMode.AfterDefaultPrefix) { routePrefix = routePrefix + "/" + autoRoutePrefix; } else if (autoRoutePrefixAttribute.Mode == AutoRoutePrefixMode.BeforeDefaultPrefix) { routePrefix = autoRoutePrefix + "/" + routePrefix; } } return(routePrefix); }
/// <summary> /// Determines whether the controller should be considered for <see cref="ApiExplorer.ApiDescriptions"/> generation. Called when initializing the <see cref="ApiExplorer.ApiDescriptions"/>. /// </summary> /// <param name="controllerVariableValue">The controller variable value from the route.</param> /// <param name="controllerDescriptor">The controller descriptor.</param> /// <param name="route">The route.</param> /// <returns><c>true</c> if the controller should be considered for <see cref="ApiExplorer.ApiDescriptions"/> generation, <c>false</c> otherwise.</returns> public virtual bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route) { if (controllerDescriptor == null) { throw Error.ArgumentNull("controllerDescriptor"); } if (route == null) { throw Error.ArgumentNull("route"); } ApiExplorerSettingsAttribute setting = controllerDescriptor.GetCustomAttributes<ApiExplorerSettingsAttribute>().FirstOrDefault(); return (setting == null || !setting.IgnoreApi) && MatchRegexConstraint(route, ControllerVariableName, controllerVariableValue); }
protected override IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(HttpControllerDescriptor controllerDescriptor) { return controllerDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true); }
private static IEnumerable<string> GetODataRoutePrefixes(HttpControllerDescriptor controllerDescriptor) { Contract.Assert(controllerDescriptor != null); var prefixAttributes = controllerDescriptor.GetCustomAttributes<ODataRoutePrefixAttribute>(inherit: false); if (prefixAttributes.Count == 0) { yield return null; } else { foreach (ODataRoutePrefixAttribute prefixAttribute in prefixAttributes) { string prefix = prefixAttribute.Prefix; if (prefix != null && prefix.StartsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation(SRResources.RoutePrefixStartsWithSlash, prefix, controllerDescriptor.ControllerType.FullName); } if (prefix != null && prefix.EndsWith("/", StringComparison.Ordinal)) { prefix = prefix.TrimEnd('/'); } yield return prefix; } } }
private static string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor) { Collection<RoutePrefixAttribute> routePrefixAttributes = controllerDescriptor.GetCustomAttributes<RoutePrefixAttribute>(inherit: false); if (routePrefixAttributes.Count > 0) { string routePrefix = routePrefixAttributes[0].Prefix; if (routePrefix != null) { if (routePrefix.EndsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation(SRResources.AttributeRoutes_InvalidPrefix, routePrefix, controllerDescriptor.ControllerName); } return routePrefix; } } return null; }
// Return null if no DefaultRouteAttribute on the controller. private static Collection<IHttpRouteInfoProvider> GetDefaultRouteTemplate(HttpControllerDescriptor controllerDescriptor) { Collection<DefaultRouteAttribute> defaultRouteAttributes = controllerDescriptor.GetCustomAttributes<DefaultRouteAttribute>(inherit: false); if ((defaultRouteAttributes == null) || (defaultRouteAttributes.Count == 0)) { return null; } // Morph a DefaultRouteAttribute into a IHttpRouteInfoProvider // Let the other properties have their default values. If the user cared about them, // they'd set the [Route] attribute on the action directly and specify them. string routeTemplate = defaultRouteAttributes[0].RouteTemplate; return new Collection<IHttpRouteInfoProvider> { new RouteAttribute(routeTemplate) }; }
/// <summary> /// Gets the route prefix from the provided controller. /// </summary> /// <param name="controllerDescriptor">The controller descriptor.</param> /// <returns>The route prefix or null.</returns> protected virtual string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor) { Collection<IRoutePrefix> attributes = controllerDescriptor.GetCustomAttributes<IRoutePrefix>(inherit: false); if (attributes == null) { return null; } if (attributes.Count > 1) { string errorMessage = Error.Format(SRResources.RoutePrefix_CannotSupportMultiRoutePrefix, controllerDescriptor.ControllerType.FullName); throw new InvalidOperationException(errorMessage); } if (attributes.Count == 1) { IRoutePrefix attribute = attributes[0]; if (attribute != null) { string prefix = attribute.Prefix; if (prefix == null) { string errorMessage = Error.Format( SRResources.RoutePrefix_PrefixCannotBeNull, controllerDescriptor.ControllerType.FullName); throw new InvalidOperationException(errorMessage); } if (prefix.EndsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation(SRResources.AttributeRoutes_InvalidPrefix, prefix, controllerDescriptor.ControllerName); } return prefix; } } return null; }
private static IEnumerable<HttpRouteEntry> CreateRouteEntries(HttpControllerDescriptor controllerDescriptor) { IHttpActionSelector actionSelector = controllerDescriptor.Configuration.Services.GetActionSelector(); ILookup<string, HttpActionDescriptor> actionMap = actionSelector.GetActionMapping(controllerDescriptor); if (actionMap == null) { return Enumerable.Empty<HttpRouteEntry>(); } List<HttpRouteEntry> routes = new List<HttpRouteEntry>(); string routePrefix = GetRoutePrefix(controllerDescriptor); List<ReflectedHttpActionDescriptor> actionsWithoutRoutes = new List<ReflectedHttpActionDescriptor>(); foreach (IGrouping<string, HttpActionDescriptor> actionGrouping in actionMap) { string actionName = actionGrouping.Key; foreach (ReflectedHttpActionDescriptor actionDescriptor in actionGrouping.OfType<ReflectedHttpActionDescriptor>()) { Collection<IHttpRouteInfoProvider> routeProviders = actionDescriptor.GetCustomAttributes<IHttpRouteInfoProvider>(inherit: false); if (routeProviders != null && routeProviders.Count > 0) { AddRouteEntries(routes, actionName, routePrefix, routeProviders, new ReflectedHttpActionDescriptor[] { actionDescriptor }); } else { // IF there are no routes on the specific action, attach it to the controller routes (if any). actionsWithoutRoutes.Add(actionDescriptor); } } } Collection<IHttpRouteInfoProvider> controllerRouteProviders = controllerDescriptor.GetCustomAttributes<IHttpRouteInfoProvider>(inherit: true); // If they exist and have not been overridden, create routes for controller-level route providers. if (controllerRouteProviders != null && controllerRouteProviders.Count > 0 && actionsWithoutRoutes.Count > 0) { AddRouteEntries(routes, actionsWithoutRoutes[0].ActionName, routePrefix, controllerRouteProviders, actionsWithoutRoutes); } return routes; }
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { var attr = controllerDescriptor.GetCustomAttributes<ApiControlAttribute>().FirstOrDefault(); return attr != null ? attr.Documentation : ""; }
public void GetCustomAttributesInheritFalse_DoesNotGetInheritedAttributes() { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor desc = new HttpControllerDescriptor(config, "MyController", typeof(MyDerived1Controller)); var attributes = desc.GetCustomAttributes<MyConfigBaseAttribute>(inherit: false); Assert.Empty(attributes); }
public void GetCustomAttributesInheritFalse_GetsDeclaredAttributes() { HttpConfiguration config = new HttpConfiguration(); HttpControllerDescriptor desc = new HttpControllerDescriptor(config, "MyController", typeof(MyDerived1Controller)); var attributes = desc.GetCustomAttributes<MyConfigDerived1Attribute>(inherit: false); Assert.Equal(1, attributes.Count); }
public static bool HasIgnoreAttribute(HttpControllerDescriptor controllerDescriptor) { return controllerDescriptor.GetCustomAttributes<SwaggerIgnoreAttribute>().Count > 0; }
private static string GetODataRoutePrefix(HttpControllerDescriptor controllerDescriptor) { Contract.Assert(controllerDescriptor != null); string prefix = controllerDescriptor.GetCustomAttributes<ODataRoutePrefixAttribute>(inherit: false) .Select(prefixAttribute => prefixAttribute.Prefix) .SingleOrDefault(); if (prefix != null && prefix.StartsWith("/", StringComparison.Ordinal)) { throw Error.InvalidOperation(SRResources.RoutePrefixStartsWithSlash, prefix, controllerDescriptor.ControllerType.FullName); } if (prefix != null && prefix.EndsWith("/", StringComparison.Ordinal)) { prefix = prefix.TrimEnd('/'); } return prefix; }
private static IEnumerable<HttpRouteEntry> CreateRouteEntries(HttpControllerDescriptor controllerDescriptor) { IHttpActionSelector actionSelector = controllerDescriptor.Configuration.Services.GetActionSelector(); ILookup<string, HttpActionDescriptor> actionMap = actionSelector.GetActionMapping(controllerDescriptor); if (actionMap == null) { return Enumerable.Empty<HttpRouteEntry>(); } List<HttpRouteEntry> routes = new List<HttpRouteEntry>(); RoutePrefixAttribute routePrefix = controllerDescriptor.GetCustomAttributes<RoutePrefixAttribute>(inherit: false).SingleOrDefault(); foreach (IGrouping<string, HttpActionDescriptor> actionGrouping in actionMap) { string actionName = actionGrouping.Key; foreach (ReflectedHttpActionDescriptor actionDescriptor in actionGrouping.OfType<ReflectedHttpActionDescriptor>()) { IEnumerable<IHttpRouteInfoProvider> routeInfoProviders = actionDescriptor.GetCustomAttributes<IHttpRouteInfoProvider>(inherit: false); foreach (IHttpRouteInfoProvider routeProvider in routeInfoProviders.DefaultIfEmpty()) { string routeTemplate = BuildRouteTemplate(routePrefix, routeProvider, controllerDescriptor.ControllerName); if (routeTemplate == null) { continue; } // Try to find an entry with the same route template and the same HTTP verbs HttpRouteEntry existingEntry = null; foreach (HttpRouteEntry entry in routes) { if (String.Equals(routeTemplate, entry.RouteTemplate, StringComparison.OrdinalIgnoreCase) && AreEqual(routeProvider.HttpMethods, entry.HttpMethods)) { existingEntry = entry; break; } } if (existingEntry == null) { HttpRouteEntry entry = new HttpRouteEntry() { RouteTemplate = routeTemplate, Actions = new HashSet<ReflectedHttpActionDescriptor>() { actionDescriptor } }; if (routeProvider != null) { entry.HttpMethods = routeProvider.HttpMethods; entry.Name = routeProvider.RouteName; entry.Order = routeProvider.RouteOrder; } routes.Add(entry); } else { existingEntry.Actions.Add(actionDescriptor); // Take the minimum of the two orders as the order int order = routeProvider == null ? 0 : routeProvider.RouteOrder; if (order < existingEntry.Order) { existingEntry.Order = order; } // Use the provider route name if the route hasn't already been named if (routeProvider != null && existingEntry.Name == null) { existingEntry.Name = routeProvider.RouteName; } } } } } return routes; }
/// <summary> /// Gets route factories for the given controller descriptor. /// </summary> /// <param name="controllerDescriptor">The controller descriptor.</param> /// <returns>A set of route factories.</returns> /// <remarks> /// The implementation returns <see cref="IDirectRouteFactory"/> instances based on attributes on the controller. /// </remarks> protected virtual IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(HttpControllerDescriptor controllerDescriptor) { Collection<IDirectRouteFactory> newFactories = controllerDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: false); Collection<IHttpRouteInfoProvider> oldProviders = controllerDescriptor.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; }