示例#1
0
 /// <summary>
 /// 添加Swagger扩展服务
 /// </summary>
 /// <param name="services">services</param>
 /// <param name="swaggerDocOptions">swaggerDocOptions</param>
 /// <returns></returns>
 public static IServiceCollection AddSwaggerExtensions(this IServiceCollection services, SwaggerDocOptions swaggerDocOptions = null)
 {
     if (swaggerDocOptions == null)
     {
         swaggerDocOptions = new SwaggerDocOptions();
     }
     AspNetCoreExtensionsConfig.SwaggerDocOptions = swaggerDocOptions;
     if (swaggerDocOptions.Enable)
     {
         services.AddSwaggerGen(c =>
         {
             c.CustomSchemaIds(i => i.FullName);
             c.SwaggerDoc(swaggerDocOptions.Name, swaggerDocOptions.OpenApiInfo);
             var enumerable = AssemblyHelper.GetAllAssemblies();
             foreach (var item in enumerable)
             {
                 var xmlName = $"{item.GetName().Name}.xml";
                 var xmlPath = item.ManifestModule.FullyQualifiedName.Replace(item.ManifestModule.Name, xmlName);
                 if (File.Exists(xmlPath))
                 {
                     c.IncludeXmlComments(xmlPath, true); //添加控制器层注释(true表示显示控制器注释)
                 }
             }
             if (swaggerDocOptions.HeaderParameters != null && swaggerDocOptions.HeaderParameters.Count > 0)
             {
                 c.OperationFilter <AddRequiredHeaderParameter>();//添加header参数
             }
         });
     }
     return(services);
 }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var docOptions = new SwaggerDocOptions {
                Name = "v1", OpenApiInfo = { Title = "WeiXinMp", Version = "v1", Description = "ÎÒÊÇÃèÊö" }
            };

            services.AddAspNetCoreExtensions(docOptions);
        }
示例#3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var docOptions = new SwaggerDocOptions {
                Name = "v1", OpenApiInfo = { Title = "WeiXinMp", Version = "v1", Description = "ÎÒÊÇÃèÊö" }, Enable = true
            };

            docOptions.HeaderParameters.Add(new HeaderParameter()
            {
                Name = "token", Value = ""
            });
            services.AddAspNetCoreExtensions(docOptions);
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();

            var swaggerDocOptions = new SwaggerDocOptions();

            Configuration.GetSection(nameof(SwaggerDocOptions)).Bind(swaggerDocOptions);

            services.AddSwaggerGen(swagger =>
            {
                swagger.SwaggerDoc(swaggerDocOptions.Version, new OpenApiInfo
                {
                    Title       = swaggerDocOptions.Title,
                    Version     = swaggerDocOptions.Version,
                    Description = swaggerDocOptions.Description,
                    Contact     = new OpenApiContact
                    {
                        Name = swaggerDocOptions.Organization
                    }
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                swagger.IncludeXmlComments(xmlPath);
            });



            // Register InvestEdge.Application Service Configurations
            services.AddApplication();

            // Add InvestEdge.Infrastructure Service Configuration
            services.AddInfrastructure(Configuration, Environment);

            services.AddControllers()
            .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>());;
        }
示例#5
0
 /// <summary>
 /// 添加Swagger扩展服务
 /// </summary>
 /// <param name="services">services</param>
 /// <param name="swaggerDocOptions">swaggerDocOptions</param>
 /// <returns></returns>
 public static IServiceCollection AddSwaggerExtensions(this IServiceCollection services, SwaggerDocOptions swaggerDocOptions = null)
 {
     if (swaggerDocOptions == null)
     {
         swaggerDocOptions = new SwaggerDocOptions();
     }
     AspNetCoreExtensionsConfig.SwaggerDocOptions = swaggerDocOptions;
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc(swaggerDocOptions.Name, swaggerDocOptions.OpenApiInfo);
         var enumerable = AssemblyHelper.GetAllAssemblies();
         foreach (var item in enumerable)
         {
             var xmlName = $"{item.GetName().Name}.xml";
             var xmlPath = item.ManifestModule.FullyQualifiedName.Replace(item.ManifestModule.Name, xmlName);
             if (File.Exists(xmlPath))
             {
                 c.IncludeXmlComments(xmlPath, true); //添加控制器层注释(true表示显示控制器注释)
             }
         }
     });
     return(services);
 }
示例#6
0
 /// <summary>
 /// 添加AspNetCore扩展服务
 /// </summary>
 /// <param name="services">services</param>
 /// <param name="swaggerDocOptions">swaggerDocOptions</param>
 /// <returns></returns>
 public static IServiceCollection AddAspNetCoreExtensions(this IServiceCollection services, SwaggerDocOptions swaggerDocOptions = null)
 {
     services.AddSwaggerExtensions(swaggerDocOptions);
     return(services);
 }
示例#7
0
        public FunctionApiDescriptionProvider(
            IOptions <SwaggerDocOptions> functionsOptions,
            SwashBuckleStartupConfig startupConfig,
            IModelMetadataProvider modelMetadataProvider,
            ICompositeMetadataDetailsProvider compositeMetadataDetailsProvider,
            IOutputFormatter outputFormatter,
            IOptions <HttpOptions> httpOptions)
        {
            _swaggerDocOptions                = functionsOptions.Value;
            _modelMetadataProvider            = modelMetadataProvider;
            _compositeMetadataDetailsProvider = compositeMetadataDetailsProvider;
            _outputFormatter = outputFormatter;

            var apiDescGroups = new Dictionary <string, List <ApiDescription> >();
            var methods       = startupConfig.Assembly.GetTypes()
                                .SelectMany(t => t.GetMethods())
                                .Where(m => m.GetCustomAttributes(typeof(FunctionNameAttribute), false).Any())
                                .ToArray();

            foreach (var methodInfo in methods)
            {
                if (!TryGetHttpTrigger(methodInfo, out var triggerAttribute))
                {
                    continue;
                }

                var functionAttr =
                    (FunctionNameAttribute)methodInfo.GetCustomAttribute(typeof(FunctionNameAttribute), false);
                var apiExplorerSettingsAttribute =
                    (ApiExplorerSettingsAttribute)methodInfo.GetCustomAttribute(typeof(ApiExplorerSettingsAttribute),
                                                                                false) ??
                    (ApiExplorerSettingsAttribute)methodInfo.DeclaringType.GetCustomAttribute(
                        typeof(ApiExplorerSettingsAttribute), false);

                var prefix = string.IsNullOrWhiteSpace(httpOptions.Value.RoutePrefix)
                    ? string.Empty
                    : $"{httpOptions.Value.RoutePrefix.TrimEnd('/')}/";

                string route;

                if (_swaggerDocOptions.PrependOperationWithRoutePrefix)
                {
                    var routePart = !string.IsNullOrWhiteSpace(triggerAttribute.Route)
                        ? triggerAttribute.Route
                        : functionAttr.Name;

                    route = $"{prefix}{(routePart)}";
                }
                else
                {
                    route = !string.IsNullOrWhiteSpace(triggerAttribute.Route)
                        ? triggerAttribute.Route
                        : functionAttr.Name;
                }

                var routes = new List <(string Route, string RemoveParamName)>();

                var regex = new Regex("/\\{(?<paramName>\\w+)\\?\\}$");
                var match = regex.Match(route);

                var routeParamRemoveRegex = new Regex(":[a-zA-Z]+(\\(.*\\))?");
                route = routeParamRemoveRegex.Replace(route, "");

                if (match.Success && match.Captures.Count == 1)
                {
                    routes.Add(
                        (route.Replace(match.Value, "").Replace("//", "/"), match.Groups["paramName"].ToString()));
                    routes.Add((route.Replace(match.Value, match.Value.Replace("?", "")), ""));
                }
                else
                {
                    routes.Add((route, ""));
                }

                var verbs = triggerAttribute.Methods ??
                            new[] { "get", "post", "delete", "head", "patch", "put", "options" };


                for (var index = 0; index < routes.Count; index++)
                {
                    var routeTuple = routes[index];
                    var apiName    = functionAttr.Name + (index == 0 ? "" : $"-{index}");
                    var items      = verbs.Select(verb =>
                                                  CreateDescription(methodInfo, routeTuple.Route, index, functionAttr, apiExplorerSettingsAttribute, verb,
                                                                    triggerAttribute.AuthLevel, routeTuple.RemoveParamName, verbs.Length > 1)).ToArray();

                    var groupName =
                        (items.FirstOrDefault()?.ActionDescriptor as ControllerActionDescriptor)?.ControllerName ??
                        apiName;
                    if (!apiDescGroups.ContainsKey(groupName))
                    {
                        apiDescGroups[groupName] = new List <ApiDescription>();
                    }

                    apiDescGroups[groupName].AddRange(items);
                }
            }

            ApiDescriptionGroups =
                new ApiDescriptionGroupCollection(
                    new ReadOnlyCollection <ApiDescriptionGroup>(
                        apiDescGroups.Select(kv => new ApiDescriptionGroup(kv.Key, kv.Value)).ToList()
                        ), 1);
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // needed to load configuration from appsettings.json
            services.AddOptions();

            // needed to store rate limit counters and ip rules
            services.AddMemoryCache();

            //load general configuration from appsettings.json
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

            // inject counter and rules stores
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            // Register CurrentUserService
            services.AddScoped <ICurrentUserService, CurrentUserService>();

            // the clientId/clientIp resolvers use it.
            //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpContextAccessor();

            // Register and configure localization services
            services.AddLocalization(options => options.ResourcesPath = "Localization");

            services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

            // confiure HTTP Strict Transport Security Protocol (HSTS)
            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(1);
            });

            // configuration (resolvers, counter key builders)
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            // Register and configure CORS
            services.AddCors(options =>
            {
                options.AddPolicy(name: "CorsPolicy",
                                  builder =>
                {
                    builder.WithOrigins("https://localhost")
                    .WithMethods("OPTIONS", "GET", "POST", "PUT", "DELETE")
                    .AllowCredentials();
                });
            });

            // Register and Configure API versioning
            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
            });

            //Register and configure API versioning explorer
            services.AddVersionedApiExplorer(option =>
            {
                option.GroupNameFormat           = "'v'VVV";
                option.SubstituteApiVersionInUrl = true;
            });

            // Swagger OpenAPI Configuration
            var swaggerDocOptions = new SwaggerDocOptions();

            Configuration.GetSection(nameof(SwaggerDocOptions)).Bind(swaggerDocOptions);
            services.AddSwaggerGen();
            services.AddOptions <SwaggerGenOptions>()
            .Configure <IApiVersionDescriptionProvider>((swagger, service) =>
            {
                foreach (ApiVersionDescription description in service.ApiVersionDescriptions)
                {
                    swagger.SwaggerDoc(description.GroupName, new OpenApiInfo
                    {
                        Title       = swaggerDocOptions.Title,
                        Version     = description.ApiVersion.ToString(),
                        Description = swaggerDocOptions.Description,
                        Contact     = new OpenApiContact
                        {
                            Name  = swaggerDocOptions.Organization,
                            Email = swaggerDocOptions.Email
                        }
                    });
                }

                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[0] }
                };

                swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme.",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

                /*swagger.AddSecurityRequirement(new OpenApiSecurityRequirement()
                 * {
                 *  {
                 *      new OpenApiSecurityScheme
                 *      {
                 *          Reference = new OpenApiReference
                 *          {
                 *              Type = ReferenceType.SecurityScheme,
                 *              Id = "Bearer"
                 *          },
                 *          Scheme = "oauth2",
                 *          Name = "Bearer",
                 *          In = ParameterLocation.Header,
                 *
                 *      },
                 *      new List<string>()
                 *  }
                 * });*/

                swagger.OperationFilter <AuthorizeCheckOperationFilter>();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                swagger.IncludeXmlComments(xmlPath);
            });

            // Register InvestEdge.Application Service Configurations
            services.AddApplication();

            // Add InvestEdge.Infrastructure Service Configuration
            services.AddPersistence(Configuration);

            // Add InvestEdge.Infrastructure Service Configuration
            services.AddInfrastructure(Configuration, Environment);

            services.AddControllers()
            .AddNewtonsoftJson()
            .AddFluentValidation(options =>
                                 options.RegisterValidatorsFromAssemblyContaining <Startup>());

            // Customise default API behaviour
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
        }
示例#9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();

            // Configure Swagger Docs
            var swaggerDocOptions = new SwaggerDocOptions();

            Configuration.GetSection(nameof(SwaggerDocOptions)).Bind(swaggerDocOptions);

            services.AddSwaggerGen(swagger =>
            {
                swagger.SwaggerDoc(swaggerDocOptions.Version, new OpenApiInfo
                {
                    Title       = swaggerDocOptions.Title,
                    Version     = swaggerDocOptions.Version,
                    Description = swaggerDocOptions.Description,
                    Contact     = new OpenApiContact
                    {
                        Name = swaggerDocOptions.Organization
                    },
                    License = new OpenApiLicense
                    {
                        Name = "MIT License",
                        Url  = new Uri("https://github.com/marlonajgayle/LifeBank/blob/master/LICENSE.md"),
                    }
                });

                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[0] }
                };

                swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme.",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

                swagger.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                swagger.IncludeXmlComments(xmlPath);
            });

            services.AddSwaggerGenNewtonsoftSupport();

            // Add LifeBank.Application Service Configurations
            services.AddApplication();

            // Add LifeBank.Infrastructure Service Configuration
            services.AddInfrastructure(Configuration, Environment);

            services
            .AddControllers()
            .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>());
        }
示例#10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // needed to load configuration from appsettings.json
            services.AddOptions();

            // needed to store rate limit counters and ip rules
            services.AddMemoryCache();

            //load general configuration from appsettings.json
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

            // inject counter and rules stores
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            // the clientId/clientIp resolvers use it.
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // configuration (resolvers, counter key builders)
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            //enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();

            // get CORS Options
            var corsPolicyOptions = new CorsPolicyOptions();

            Configuration.GetSection(nameof(CorsPolicyOptions)).Bind(corsPolicyOptions);
            CorsPolicyName = corsPolicyOptions.Name;

            services.AddCors(options => // Make sure you call this previous to AddMvc
            {
                options.AddPolicy(name: corsPolicyOptions.Name,
                                  builder =>
                {
                    builder.WithOrigins(corsPolicyOptions.Origin)
                    .WithHeaders(HeaderNames.ContentType, corsPolicyOptions.JsonHeader)
                    .WithMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .AllowCredentials();
                });
            });

            var swaggerDocOptions = new SwaggerDocOptions();

            Configuration.GetSection(nameof(SwaggerDocOptions)).Bind(swaggerDocOptions);

            services.AddSwaggerGen(swagger =>
            {
                swagger.SwaggerDoc(swaggerDocOptions.Version, new OpenApiInfo
                {
                    Title       = swaggerDocOptions.Title,
                    Version     = swaggerDocOptions.Version,
                    Description = swaggerDocOptions.Description,
                    Contact     = new OpenApiContact
                    {
                        Name = swaggerDocOptions.Organization
                    }
                });

                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[0] }
                };

                swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme.",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

                swagger.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                swagger.IncludeXmlComments(xmlPath);
            });

            // Register InvestEdge.Application Service Configurations
            services.AddApplication();

            // Add InvestEdge.Infrastructure Service Configuration
            services.AddInfrastructure(Configuration, Environment);

            services.AddControllers()
            .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>());;
        }