コード例 #1
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var _serviceFilter = new ServiceFilterAttribute(typeof(AuthAttribute));

            if (operation.Parameters == null)
            {
                operation.Parameters = new List <IParameter>();
            }
            var actionAttrs  = context.ApiDescription.ActionAttributes();
            var isAuthorized = actionAttrs.Any(a => a.GetType() == _serviceFilter.GetType());

            if (isAuthorized == false) //提供action都没有权限特性标记,检查控制器有没有
            {
                var controllerAttrs = context.ApiDescription.ControllerAttributes();
                isAuthorized = controllerAttrs.Any(a => a.GetType() == _serviceFilter.GetType());
            }

            if (isAuthorized)
            {
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name     = "Authorization", //添加Authorization头部参数
                    In       = "header",
                    Type     = "string",
                    Required = false
                });
            }
        }
コード例 #2
0
    public void CreateService_UnwrapsFilterFactory()
    {
        // Arrange
        var serviceProvider = new ServiceCollection()
                              .AddSingleton(new TestFilterFactory())
                              .BuildServiceProvider();

        var serviceFilter = new ServiceFilterAttribute(typeof(TestFilterFactory));

        // Act
        var filter = serviceFilter.CreateInstance(serviceProvider);

        // Assert
        Assert.IsType <TestFilter>(filter);
    }
コード例 #3
0
    public void CreateService_GetsFilterFromServiceProvider()
    {
        // Arrange
        var expected        = new TestFilter();
        var serviceProvider = new ServiceCollection()
                              .AddSingleton(expected)
                              .BuildServiceProvider();

        var serviceFilter = new ServiceFilterAttribute(typeof(TestFilter));

        // Act
        var filter = serviceFilter.CreateInstance(serviceProvider);

        // Assert
        Assert.Same(expected, filter);
    }
コード例 #4
0
        /// <summary>
        /// Adds a type representing an <see cref="IFilterMetadata"/>.
        /// </summary>
        /// <param name="filterType">Type representing an <see cref="IFilterMetadata"/>.</param>
        /// <param name="order">The order of the added filter.</param>
        /// <returns>An <see cref="IFilterMetadata"/> representing the added service type.</returns>
        /// <remarks>
        /// Filter instances will created through dependency injection. Use
        /// <see cref="Add(Type)"/> to register a service that will be created via
        /// type activation.
        /// </remarks>
        public IFilterMetadata AddService([NotNull] Type filterType, int order)
        {
            if (!typeof(IFilterMetadata).GetTypeInfo().IsAssignableFrom(filterType.GetTypeInfo()))
            {
                var message = Resources.FormatTypeMustDeriveFromType(
                    filterType.FullName,
                    typeof(IFilterMetadata).FullName);
                throw new ArgumentException(message, nameof(filterType));
            }

            var filter = new ServiceFilterAttribute(filterType)
            {
                Order = order
            };

            Add(filter);
            return(filter);
        }
コード例 #5
0
        /// <summary>
        ///     Adds a type to a <see cref="FilterCollection" /> if it doesn't already exist.
        /// </summary>
        /// <typeparam name="TType">The type of the t type.</typeparam>
        /// <param name="col">The col.</param>
        /// <param name="order">Filter order</param>
        /// <returns>FilterCollection.</returns>
        public static FilterCollection TryAdd <TType>(this FilterCollection col, int?order = null)
            where TType : IFilterMetadata
        {
            var vt = typeof(TType);

            if (col.All(t =>
            {
                // Yet more lameness, really should be able to do a simple test here...
                return(t switch
                {
                    TypeFilterAttribute tf => tf.ImplementationType != vt,
                    ServiceFilterAttribute sf => sf.ServiceType != vt,
                    FormatFilterAttribute ff => ff.GetType() != vt,
                    ResultFilterAttribute rs => rs.GetType() != vt,
                    ExceptionFilterAttribute ef => ef.GetType() != vt,
                    ActionFilterAttribute af => af.GetType() != vt,
                    _ => t.GetType() != vt
                });
            }
コード例 #6
0
ファイル: FilterValuesTest.cs プロジェクト: rkakadia/Mvc-1
        public void ServiceFilterAttribute_InitializesCorrectValues()
        {
            // Arrange
            var filter = new ServiceFilterAttribute(typeof(TestFilter));

            // Act
            var filterValues = new FilterValues(filter);

            // Assert
            Assert.True(filterValues.IsFactory);
            Assert.Equal(typeof(TestFilter), filterValues.FilterType);
            Assert.Equal(typeof(ServiceFilterAttribute), filterValues.FilterMetadataType);
            Assert.Equal(
                new List <Type>()
            {
                typeof(IFilter), typeof(IExceptionFilter)
            },
                filterValues.FilterInterfaces);
        }
コード例 #7
0
        /// <summary>
        /// ConfigureServices is where you register dependencies. This gets called by the runtime
        /// before the Configure method, below.
        /// </summary>
        /// <param name="services">Specifies the contract for a collection of service descriptors.</param>
        /// <returns>Un IServiceProvider.</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add services to the collection.
            IMvcBuilder mvcBuilder = services.AddMvc();

            // Configura el manejador global de excepciones.
            services.AddSingleton <GlobalExceptionFilter>();

            // Setup global exception filters.
            mvcBuilder.AddMvcOptions(
                options =>
            {
                FilterCollection filters = options.Filters;
                ServiceFilterAttribute exceptionFilter =
                    new ServiceFilterAttribute(typeof(GlobalExceptionFilter));
                filters.Add(exceptionFilter);

                // ServiceFilterAttribute validationFilter = new ServiceFilterAttribute(typeof(ValidateModelFilter));
                filters.Add(typeof(ValidateModelFilter));
            });

            // Doc: https://github.com/domaindrivendev/Swashbuckle.AspNetCore
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Training.Persona.Api", Version = "v1"
                });
                c.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Training.Persona.Api.xml"));
                c.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Training.Persona.Entities.xml"));
                c.DescribeAllEnumsAsStrings();
                c.IgnoreObsoleteActions();
                c.OperationFilter <SwaggerGenResponseFilter>();
            });

            // Create the container builder.
            ContainerBuilder builder = new ContainerBuilder();

            // Register dependencies, populate the services from the collection, and build the container.
            builder.Populate(services);

            // Registra la configuración (appsettings.json).
            builder.RegisterInstance(this.Configuration).AsImplementedInterfaces().SingleInstance();

            builder.RegisterModule <Persona.Ioc.PersonaModule>();

            // Registra y mapea los Settings (ConnectionStrings).
            builder.Register(
                c =>
            {
                // Resuelve el ConfigurationRoot.
                IConfigurationRoot configurationRoot = c.Resolve <IConfigurationRoot>();

                // Obtiene la sección del .json de settings.
                IConfigurationSection section = configurationRoot.GetSection("ConnectionStrings");

                // Mapea la sección del .json a la clase.
                Apollo.NetCore.Core.Settings.ConnectionStrings connStr = new Apollo.NetCore.Core.Settings.ConnectionStrings();
                ConfigurationBinder.Bind(section, connStr);

                return(connStr);
            }).As <Apollo.NetCore.Core.Settings.ConnectionStrings>()

            .SingleInstance();

            this.ApplicationContainer = builder.Build();

            // Create the IServiceProvider based on the container.
            return(new AutofacServiceProvider(this.ApplicationContainer));
        }