Swagger .NetCore没有将外包的启动生成swagger.json

时间:2018-12-04 10:20:12

标签: c# .net-core swagger

我们尝试使用.NetCore中的IdentityServer4来实现。

现在,如果我使用API​​和以下startup.cs设置.NetCore项目,则一切正常,并且Swagger中显示了该API

public class MyStartup
{
    public MyStartup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", true, false)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, false)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    protected IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddApiExplorer()
            .AddVersionedApiExplorer(
                options =>
                {
                    options.GroupNameFormat = "'v'V";

                    // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
                    // can also be used to control the format of the API version in route templates
                    options.SubstituteApiVersionInUrl = true;
                })
            .AddAuthorization(ConfigureAuthorization)
            .AddFormatterMappings()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            //.AddDataAnnotations()
            .AddJsonFormatters(MyWebApiFormattersConfig.SetJsonSerializerSettings)
            //.AddCors()
            //Add mvc options last - won't work in AddMvcCore.
            .AddMvcOptions(ConfigureMvc);

        services.AddHttpContextAccessor();
        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://dev.idserver.my.ch/"; // auth server base endpoint (will use to search for disco doc)
                options.ApiName = "MySwagger"; // required audience of access tokens
                options.RequireHttpsMetadata = false; // dev only!
            });

        var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
        if (JsonCustomizingConfig.GetSwaggerIsEnabled(Configuration))
        {
            var securityScheme = new OAuth2Scheme()
            {
                AuthorizationUrl = JsonCustomizingConfig.GetSwaggerOAuthUrl(Configuration),
                //TokenUrl = JsonCustomizingConfig.GetSwaggerOAuthTokenUrl(config),
                Flow = JsonCustomizingConfig.GetSwaggerOAuthFlow(Configuration),
                Scopes = JsonCustomizingConfig.GetSwaggerOAuthScopes(Configuration),
            };

            services.AddSwaggerGen(options =>
            {
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(description.GroupName, new Info
                    {
                        Title = $"My API {description.ApiVersion}",
                        Version = description.ApiVersion.ToString(),
                        Description = "My API",
                        Contact = new Contact() { Name = "my:solutions AG", Email = "info@my.ch" }
                    });
                }

                options.AddSecurityDefinition("My swagger", securityScheme);
                options.OperationFilter<AuthorizeCheckOperationFilter>(); // Required to use access token
            });
        }
        services.AddApiVersioning(MyApiConfig.ConfigureVersioning);
        services.AddSingleton(Configuration);
    }

    private void ConfigureMvc(MvcOptions options)
    {
        options.Filters.Add(new MyAuthorizeFilter("MyAuthPolicy"));
    }

    private void ConfigureAuthorization(AuthorizationOptions options)
    {
        options.AddPolicy("MyAuthPolicy", p =>
        {
            p.RequireAuthenticatedUser();
            //p.RequireClaim(My.Def.Permission.MyClaimTypes.SysKundeId);
            p.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        });
        options.DefaultPolicy = options.GetPolicy("MyAuthPolicy");
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
    {
        app.UseAuthentication();
        app.UseMvc();

        if (JsonCustomizingConfig.GetSwaggerIsEnabled(Configuration))
        {
            // Swagger JSON Doc
            app.UseSwagger();

            // Swagger UI
            app.UseSwaggerUI(options =>
            {
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"My API {description.GroupName.ToUpperInvariant()}");
                }
                //options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                options.RoutePrefix = string.Empty;

                options.OAuthClientId("mySwagger");
                options.OAuthAppName("My Api"); // presentation purposes only
            });

        }

    }
}

和programm.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .ConfigureServices(services => services.AddServiceContext())
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<MyStartup>();
}

如果我将另一个项目中的startup.cs复制并粘贴到作为NuGet包添加到我的原始项目中,则该API将不再显示,并且不会生成swagger.json。 我在网上浏览了所有示例,但看不到为什么它不起作用。我希望有人可以在这里帮助我。

0 个答案:

没有答案