Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger .NETCORE can't read json

I'm having a trouble with swagger in .netcore. I've tried everything and nothing. I saw another similar questions, but nothing works for me. Running my webapi app with swagger, always returns "Can't read swagger JSON from http://localhost:5000/api/swagger/v1/swagger.json".

My codes:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                .AllowAnyMethod()
                                                                .AllowAnyHeader()));
    services.AddMvc();
    services.AddSwaggerGen();

    services.ConfigureSwaggerGen(options =>
    {
        var info = new Info
        {
            Version = "v1",
            Title = "Web API Multiprodutos",
            Description = "Web API Multiprodutos",
            Contact = new Contact { Name = "Marcos Monte", Url = "www.arrowbus.com.br" }
        };

        options.SingleApiVersion(info);

        string caminhoAplicacao = AppContext.BaseDirectory;
        string nomeAplicacao =
            PlatformServices.Default.Application.ApplicationName;
        string caminhoXmlDoc =
            Path.Combine(caminhoAplicacao, $"{nomeAplicacao}.xml");

        options.IncludeXmlComments(caminhoXmlDoc);
        options.IgnoreObsoleteProperties();
        options.IgnoreObsoleteActions();
        options.DescribeAllEnumsAsStrings();
    });

    services.AddTransient<IServicoSimulacao, ServicoSimulacao>();

    services.AddTransient<IAplicacaoLocalidade, AplicacaoEndereco>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();
    app.UseApplicationInsightsExceptionTelemetry();

    app.UseCors(builder =>
    {
        builder.AllowAnyOrigin();
        builder.AllowAnyMethod();
        builder.AllowAnyHeader();
    });

    app.UseCors("AllowAll");

    app.UseMvc();
    app.UseMvcWithDefaultRoute();

    app.UseSwagger((httpRequest, swaggerDoc) =>
    {
        swaggerDoc.Host = httpRequest.Host.Value;
    });

    app.UseSwaggerUi(swaggerUrl: Configuration["AppSettings:VirtualDirectory"] + "/swagger/v1/swagger.json", baseRoute: "swagger/ui");
}

Project.json

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Aplicacao.Multiprodutos": "1.0.0-*",
    "Dominio.MultiProdutos": "1.0.0-*",
    "Swashbuckle": "6.0.0-beta902",
    "Swashbuckle.AspNetCore": "1.0.0",
    "Swashbuckle.SwaggerGen": "6.0.0-beta902",
    "Swashbuckle.SwaggerUi": "6.0.0-beta902",
    "Infra.Repositorio.MultiProdutos": "1.0.0-*"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "xmlDoc": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Please, help me.Thanks in advance.

UPDATE

I'm using now VS 2017 and .NET Core 1.1, but the problem remains. New code below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();

    services.AddMvc();

    services.AddCors(options =>
                        options.AddPolicy("AllowAll",
                        p => p.AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader()));



    // Register the Swagger generator, defining one or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "Web API Multiprodutos",
            Description = "Web API Multiprodutos",
            Contact = new Contact { Name = "Marcos Monte", Url = "www.arrowbus.com.br" }
        });

        string caminhoAplicacao = AppContext.BaseDirectory;
        string nomeAplicacao =
            PlatformServices.Default.Application.ApplicationName;
        string caminhoXmlDoc =
            Path.Combine(caminhoAplicacao, $"swagger.xml");

        c.IncludeXmlComments(caminhoXmlDoc);
        c.IgnoreObsoleteProperties();
        c.IgnoreObsoleteActions();
        c.DescribeAllEnumsAsStrings();
    });

    //Contextos
    services.AddDbContext<ADFContexto>();
    services.AddDbContext<MPFIndicacaoContexto>();
    services.AddDbContext<MPFContexto>();

    //Aplicaçãões
    services.AddScoped<IAplicacaoAtendimento, AplicacaoAtendimento>();
    services.AddScoped<IAplicacaoLocalidade, AplicacaoEndereco>();
    services.AddScoped<IAplicacaoEndereco, AplicacaoEndereco>();
    services.AddScoped<IAplicacaoTelefone, AplicacaoTelefone>();
    services.AddScoped<IAplicacaoEsteira, AplicacaoEsteira>();
    services.AddScoped<IAplicacaoCliente, AplicacaoCliente>();
    services.AddScoped<IAplicacaoLoja, AplicacaoLoja>();

    //Serviços
    services.AddScoped<IServicoSimulacao, ServicoSimulacao>();
    services.AddScoped<IServicoAtendimento, ServicoAtendimento>();


    //Repositorios
    services.AddScoped<IRepositorioFichaFinanceira, RepositorioFichaFinanceira>();
    services.AddScoped<IRepositorioEmprestimo, RepositorioEmprestimo>();
    services.AddScoped<IRepositorioCliente, RepositorioCliente>();
    services.AddScoped<IRepositorioProdutosOportunidade, RepositorioProdutoOportunidade>();
    services.AddScoped<IRepositorioAtendimento, RepositorioAtendimento>();
    services.AddScoped<IRepositorioIndicacao, RepositorioIndicacao>();
    services.AddScoped<IRepositorioEndereco, RepositorioEndereco>();
    services.AddScoped<IRepositorioTelefone, RepositorioTelefone>();
    services.AddScoped<IRepositorioHistoricoAtendimento, RepositorioHistoricoAtendimento>();
    services.AddScoped<IRepositorioEsteira, RepositorioEsteira>();
    services.AddScoped<IRepositorioLoja, RepositorioLoja>();
    services.AddScoped<IRepositorioCampanha, RepositorioCampanha>();
    services.AddScoped<IRepositorioStatus, RepositorioStatus>();
    services.AddScoped<IRepositorioSimulacao, RepositorioSimulacao>();
    services.AddScoped<IRepositorioUsuario, RepositorioUsuario>();
    services.AddScoped<IAutenticacaUsuario, AutenticacaoUsuarioHydra>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{

    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseStaticFiles();

    ConfigureAuth(app);

    app.UseCors(builder =>
    {
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
        builder.AllowAnyOrigin();
    });

    app.UseCors("AllowAll");


    app.UseMvc();
    app.UseMvcWithDefaultRoute();

    app.UseSwagger(c => { c.RouteTemplate = "{apiVersion}/swagger.json"; });

    //specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
         c.SwaggerEndpoint("v1/swagger.json", "Some API");
    });
}
like image 398
Leila Avatar asked Jun 09 '17 17:06

Leila


People also ask

Where is Swagger v1 Swagger JSON?

Add and configure Swagger middleware Launch the app and navigate to https://localhost:<port>/swagger/v1/swagger.json . The generated document describing the endpoints appears as shown in OpenAPI specification (openapi. json). The Swagger UI can be found at https://localhost:<port>/swagger .

Where is Swagger JSON saved?

Launch the app, and navigate to http://localhost:<port>/swagger/v1/swagger.json . The generated document describing the endpoints appears as shown in Swagger specification (swagger. json). The Swagger UI can be found at http://localhost:<port>/swagger .


2 Answers

adding a relative path in swaggerUi will solve the problem

app.UseSwaggerUI(c =>
{
   c.SwaggerEndpoint("../swagger/v1/swagger.json", "My API V1");
});
like image 145
aditya mukkawar Avatar answered Oct 05 '22 03:10

aditya mukkawar


Try this in your Configure():

app.UseSwagger(c => c.RouteTemplate = "api/{documentName}/swagger.json");
app.UseSwaggerUI(c => c.SwaggerEndpoint("/api/v1/swagger.json", "YourAPI V1"));

note: {documentName} parameter

This helped me: https://github.com/domaindrivendev/Swashbuckle.AspNetCore#swashbuckleaspnetcoreswagger

like image 45
Justin J. Avatar answered Oct 05 '22 04:10

Justin J.