Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swagger .NETCORE can't read json #416

Closed
leilasoriano opened this issue Jun 9, 2017 · 13 comments
Closed

Swagger .NETCORE can't read json #416

leilasoriano opened this issue Jun 9, 2017 · 13 comments

Comments

@leilasoriano
Copy link

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.

@hydanjan
Copy link

hydanjan commented Jun 9, 2017

what does VirtualDirectory return?
Configuration["AppSettings:VirtualDirectory"]

@leilasoriano
Copy link
Author

Returns "/api"

@hydanjan
Copy link

hydanjan commented Jun 9, 2017

If you want to customize the URL it has to be done in two middlewares like below.
Change the code accordingly and try accessing the json.

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

        });

@leilasoriano
Copy link
Author

I've changed and got "Additional information: Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to activate 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'."

@hydanjan
Copy link

hydanjan commented Jun 9, 2017

Sorry i gave an answer related to the Swashbuckle.AspNetCore but looks like you are not using that.
I think someone else would jump in to resolve it.

@leilasoriano
Copy link
Author

I'm using Swashbuckle.AspNetCore.

@leilasoriano
Copy link
Author

I realized the error occurs in Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }

@kvvnbabu
Copy link

kvvnbabu commented Jun 11, 2017

Try this
app.UseSwagger(c => { c.RouteTemplate = "api/swagger/{documentName}/swagger.json"; }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "Some API"); c.RoutePrefix = "api/swagger"; });

This should work.

@leilasoriano
Copy link
Author

Throws the same exception: Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to activate 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'.

@tillig
Copy link

tillig commented Jun 15, 2017

@leilasoriano Looking at your project.json it appears you have some odd packages.

For example, I see you've got the correct latest Swashbuckle.AspNetCore package (1.0.0) but you also have the original Swashbuckle package (not used in the ASP.NET Core scenario); and you also have the 6.0.0-beta* packages for Swashbuckle.SwaggerGen and Swashbuckle.SwaggerUi (also not used in ASP.NET Core).

Have you tried removing all Swashbuckle package references except for the Swashbuckle.AspNetCore package?

Note it also looks like you haven't actually moved to the final .NET Core build/app tooling, which could affect your ability to reach success. .NET Core and the dotnet CLI moved away from project.json at release time.

@tillig
Copy link

tillig commented Jun 15, 2017

The README on this repo also has a relevant note:


📣 Attention early adopters - please note the package rename to Swashbuckle.AspNetCore
If you've been using Swashbuckle for ASP.NET Core since it's inception, you may be referencing "Swashbuckle.6.0.0-beta*" packages. These are no longer valid. The original intention had been to move the Swashbuckle project from ASP.NET WebApi onto the ASP.NET Core stack in a major version bump. However, now that Microsoft plans to support WebApi for at least 4 more years, I felt it was more appropriate to split into separate projects, allowing both to live on with their respective frameworks. Although, I personally will be devoting most of my time to this version.

@pavankumargooty
Copy link

Did it got fixed for you. I am also facing similar issue

@domaindrivendev
Copy link
Owner

For anyone experiencing this issue, please ensure you have the latest version of Swashbuckle.AspNetCore - v2.5.0 at the time of writing. If you've pulled that down and still experience this issue, let me know and I'll re-open the ticket.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants