domaindrivendev / Swashbuckle.AspNetCore

Swagger tools for documenting API's built on ASP.NET Core
MIT License
5.26k stars 1.32k forks source link

[Feature] Generate Swagger file at postbuild without running the app #541

Closed ghost closed 6 years ago

ghost commented 7 years ago

Feature Request

It would be great to generate the Swagger file in CI without running the app. I am willing to build such a feature (either in this repo or create another tool). Using reflection, a small program could read all docs and generate the swagger file.

What are your comments about it?

domaindrivendev commented 7 years ago

@poulad-rbc - this is definitely a feature that's long overdue. I'm working on some significant refactors to make the overall architecture more flexible and ultimately allow this feature to "plug-in" more seamlessly. So, you might want to hold off on your PR until then.

In the meantime you could certainly start spiking into what it would take to generate the Swagger outside of the running application from a command line tool. The tricky part will be getting the complete ApiExplorer infrastructure wired up as Swashbuckle is heavily dependent on it. Easiest thing might be an in memory/test server - you could look at the current IntegrationTests for some inspiration.

When you have a design in mind, it may be prudent to talk through it before you start knocking out the PR, just so we're on the same page. Thanks

PaulDotNet commented 7 years ago

I did a very small experiment to get swagger in test/WebSites/Basic project. Here is the code in the main() function:

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

        // Trying to get swagger provider here
        var sw = (ISwaggerProvider) host.Services.GetService(typeof(ISwaggerProvider));
        // ... and document here. Which throws exception when it tries to add duplicate "x-purpose" in
        // the AssignOperationVendorExtensions.Apply()
        var doc = sw.GetSwagger("v1", null, "/");

        host.Run();
    }

As you can see from my comments this approach currently does not work. GetService() call breaks something and both sw.GetSwagger and host.Run() fails. If I remove GetSwagger() failure remains.
Any ideas why is this happening?

qmfrederik commented 6 years ago

@PaulDotNet Your code actually works for me; and here's how I serialize the swagger documentation:

// Serialize
var swaggerString = JsonConvert.SerializeObject(
    swaggerDoc,
    Formatting.Indented,
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        ContractResolver = new SwaggerContractResolver(new JsonSerializerSettings())
    });

File.WriteAllText("swagger.json", swaggerString);
qmfrederik commented 6 years ago

Actually, the code fails on .NET Core SDK 2.1.3 and works with .NET Core SDK 2.1.4. So it looks you'd need .NET Core SDK 2.1.4 for this to work 😄 .

awarrenlove commented 6 years ago

I came across this thread looking for a similar solution, specifically to write the doc statically during a build rather than only dynamically at runtime. I used the ideas here to update my Main method to this.

public static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "swagger")
    {
        Console.WriteLine(GenerateSwagger(args));
    }
    else
    {
        BuildWebHost(args).Run();
    }
}

private static string GenerateSwagger(string[] args)
{
    var host = BuildWebHost(args.Skip(2).ToArray()); // Skip the `swagger <doc-name>` arguments provided
    var sw = (ISwaggerProvider)host.Services.GetService(typeof(ISwaggerProvider));
    var doc = sw.GetSwagger(args[1], null, "/");
    return JsonConvert.SerializeObject(
        doc,
        Formatting.Indented,
        new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new SwaggerContractResolver(new JsonSerializerSettings())
        });
}

Now I can run dotnet run to execute the application normally or dotnet run swagger v1 to generate the Swagger doc to standard out, letting me redirect that to wherever I want during the build.

Edit: I should mention this is using the newer aspnetcore2.0 template that has the separate BuildWebHost method defined.

PaulDotNet commented 6 years ago
private static string GenerateSwagger(IWebHost host, string docName)
{
    var sw = (ISwaggerProvider)host.Services.GetService(typeof(ISwaggerProvider));
    var doc = sw.GetSwagger(docName, null, "/");
    return JsonConvert.SerializeObject(
        doc,
        Formatting.Indented,
        new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new SwaggerContractResolver(new JsonSerializerSettings())
        });
}

GenerateSwagger function after some cleanup. Just could not look at args parameter...

domaindrivendev commented 6 years ago

Preview of CLI tool is now available. See docs for more info - https://github.com/domaindrivendev/Swashbuckle.AspNetCore#dotnet-swagger-cli-tool. Please try out and provide feedback here

tillig commented 6 years ago

It'd be nice if the tool dumped to Console.Out by default or allowed a -- sort of output parameter to avoid writing the file. That would be friendlier to things like PowerShell pipelines where additional filtering or processing during a build might take place.

adamskoye commented 6 years ago

@domaindrivendev this is exactly what I want, thanks for your work on it - but could you please add a link to https://myget.org/feed/domaindrivendev/package/nuget/dotnet-swagger to make it easier to find?

domaindrivendev commented 6 years ago

Now available on Nuget - dotnet-swagger.1.2.0-beta1

domaindrivendev commented 6 years ago

@tillig - https://github.com/domaindrivendev/Swashbuckle.AspNetCore/commit/50067c00d982a7f51fb4dcf18bb1b470f403b24d#diff-40b7a31ddf6b8f31423fbff3dd0d5a8bR83

ranouf commented 6 years ago

Error occurred while restoring NuGet packages: Value cannot be null. Parameter name: path NU1101: Unable to find package Swashbuckle.AspNetCore.Cli. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages, nuget.org

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/601

saxonww commented 6 years ago

This is something I want to use, but right now I don't think it can work for me.

My use case is to generate a swagger document with some extensions required to deploy to/update an api gateway as part of a deployment pipeline. These extensions contain environment configuration details which I definitely do not want to expose to end users. I don't have to use swagger for this, but all of my other options are a lot more work.

I'm doing this today with Document and Operation filters. I toggle registration of the filters and provide the extra details via command line parameters; I could use appsettings/environment variables instead. My pipeline starts the application, downloads the swagger.json, then tears it down. Doing this with a cli tool would simplify my build and probably make it a little faster.

domaindrivendev commented 6 years ago

This tool still uses your Startup.cs file. So if you toggle values from within it via env variables or otherwise, they should still be picked. Can you elaborate, with examples, on why you don't think it will work for your use-case.

saxonww commented 6 years ago

I may be mistaken. I saw no discussion of or mention of ways to pass additional command line parameters, and when I run 'dotnet swagger' I get an exception about the assembly version; it looks like this project is still on an older version of Swashbuckle. I'll try upgrading.

EDIT: I do get a failure after upgrading to 2.2.0 and trying to generate a swagger document.

/path/to/Project/Project.Startup$ addSwaggerExtensions=true dotnet swagger tofile --output swagger.json ../output/Project.Startup.dll projectDoc
[18:29:34 INF] Starting up
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/home/user/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.

Unhandled Exception: System.ArgumentException: An item with the same key has already been added. Key: x-my-operation-extension
   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Common.Swashbuckle.OperationFilter.Apply(Operation operation, OperationFilterContext context) in /path/to/Common/Common.Swashbuckle/OperationFilter.cs:line 42
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreateOperation(ApiDescription apiDescription, ISchemaRegistry schemaRegistry)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItem(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry)
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath, String[] schemes)
   at Swashbuckle.AspNetCore.Cli.Program.<>c.<Main>b__0_3(IDictionary`2 namedArgs)
   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args)
   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args)
   at Swashbuckle.AspNetCore.Cli.Program.Main(String[] args)

Without addSwaggerExtensions=true I am able to generate the swagger document. If just start the application with addSwaggerExtensions=true, I can view swagger-ui and download a swagger.json with the expected content.

So this is going to work for me, but right now I'm either still running the tool incorrectly, I need to make other adjustments with the upgrade to 2.2.0, or there is a bug with the tool.

domaindrivendev commented 6 years ago

I assume PS has a way to pass environment variables to any command but you’ll have to Google the exact syntax. On Linux, you would do the following:

FOO=BAR dot net swagger

Re the exception, can you provide the stack trace?

domaindrivendev commented 6 years ago

Looks like you’re close - let me know how it goes?

saxonww commented 6 years ago

I updated my comment with the stack trace. It looks like it's coming from my code, but it only occurs when running dotnet swagger.

saxonww commented 6 years ago

What this boils down to is that CreateSwaggerProvider() is getting called twice, once during BuildWebHost() and again by GetRequiredService() in the Cli tool. I'm not sure what the correct fix for this really is - I am not very experienced with these DI frameworks - but I will send a PR with a potential fix.

x2764tech commented 6 years ago

@domaindrivendev is this still the right place to report issues with the command line tools?

I have a space in my profile path (C:\Users\David Kemp\) and I get the following error:

dotnet exec needs a managed .dll or .exe extension. The application specified was 'C:\Users\David'"

I think this is from the call to dotnet exec not wrapping the file path in double-quotes.

I can verify this by running dotnet exec with the correct path to the cli assembly.

twgraham commented 6 years ago

Love your work @domaindrivendev, my plan is to use this tool in conjunction with Atlassian's openapi-diff tool as sort of sanity test. During CI builds, my frontend SPA can compare the current API with a pre-generated version it has - thus ensuring that there are no breaking changes that my frontend might not be handling.

As for feedback, the main issue I'm having right now is getting it to work with XML comments enabled. Regular Swashbuckle.AspNetCore running on the server with comments works fine.

EDIT: My issue was self inflicted - I was trying to get the name of the file from the IHostingEnvironment ApplicationName.

fiksen99 commented 6 years ago

We're using ASP.NET Core with .NET Framework runtime, is there a plan to make this tool compatible with projects targeting .NET Framework?

x2764tech commented 6 years ago

@fiksen99 if you look at the https://github.com/domaindrivendev/Swashbuckle project, it looks like Richard doesn't have the time to maintain both versions.

I'm sure he'd appreciate a Pull Request for someone willing to port it though ;)

fiksen99 commented 6 years ago

I'm actually using the Swashbuckle.AspNetCore project right now, which is compatible with .Net Framework as it conforms to .Net standard. However from what I can see currently there isn't an equivalent of the DotNetCliReference tool in the net framework world.

I've tried to fork the current project, and add a net462 target framework (with conditional compilation around the assembly loader), I have a successful build, but alas it wasn't as easy as that and I'm unsure how to actually run the net framework app correctly (if it's even possible!) to output the swagger.

On Tue, Mar 27, 2018, 1:36 AM David Kemp notifications@github.com wrote:

@fiksen99 https://github.com/fiksen99 if you look at the https://github.com/domaindrivendev/Swashbuckle project, it looks like Richard doesn't have the time to maintain both versions.

I'm sure he'd appreciate a Pull Request for someone willing to port it though ;)

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/541#issuecomment-376442581, or mute the thread https://github.com/notifications/unsubscribe-auth/ACfI6HW2ic1gXQdtAgGoOAY3OwqxGk5Cks5tifoKgaJpZM4Qohcc .

x2764tech commented 6 years ago

It might be worth looking at how the dotnet-ef tool deals with this (although it does compilation too), as it has the ability to boostrap from aspnet core configuration/BuildWebHost the same as this cli would need to.

fiksen99 commented 6 years ago

Looks like https://www.natemcmaster.com/blog/2017/11/11/build-tools-in-nuget/ may provide insight into how we can get it working as a .Net Framework build tool. Will see if I can figure anything out here

fiksen99 commented 6 years ago

I received the following from a colleague, and have gotten relatively close to getting this working myself, but couldn't quite complete it (yet?). Indicates that it is feasible to make this work for an ASP.NET Core web app targeting .Net Framework

NuGet packages allow you to inject .targets files into the referencing projects. See https://docs.microsoft.com/en-us/nuget/create-packages/creating-a-package#including-msbuild-props-and-targets-in-a-package

One option you have here is to wrap the Swashbuckle code in an MSBuild Task. Then you can invoke that MSBuild task during your build. You can even make it happen every time you build the project if you make your target say AfterTargets="Build".

I see that the main logic of the Swashbuckle code supports net451 (https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.Swagger/Swashbuckle.AspNetCore.Swagger.csproj#L7) and the CLI tool is just a thin netcoreapp2.0 wrapper over this logic. So it should be relatively easy to wrap this code in an MSBuild task that runs on .NET Framework.

keycad commented 6 years ago

I have a problem with the version field that the CLI tool generates. I've set it all up on a AspNetCore WebApi project. Everything works fine, except that the swagger-ui generated json has the correct version number under info (1.8.14 and increasing), whereas the cli-tool generated json always has version number "2.1.0.0". I'd need to have the correct version number here, since I'm using it to generate clients and check if changes have been made to the Api

marobet commented 6 years ago

Hi @domaindrivendev ,

I'm using this tool to generate the swagger.json file, but in the Statup of my application I read settings from the launchSettings.json file using Environment.GetEnvironmentVariable("settingname"), and the values come back in null, so I'm getting exceptions when running the tool.

I read your previous reply saying:

This tool still uses your Startup.cs file. So if you toggle values from within it via env variables or otherwise, they should still be picked.

but cannot make it work with mine. Here is my code in my .csproj file.

<PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
...
 <ItemGroup>
    <DotNetCliToolReference Include="Swashbuckle.AspNetCore.Cli" Version="2.1.0-beta1" />
  </ItemGroup>
  <Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="dotnet swagger tofile --output wwwroot\api-docs\v1\swagger.json $(OutputPath)\$(AssemblyName).dll v1 " />
  </Target>

Any ideas?

Thank you

YuriGuzun commented 6 years ago

@marobet try putting '.\' before the output path and make sure path actually exists. <Exec Command="dotnet swagger tofile --output .\wwwroot\api-docs\v1\swagger.json $(OutputPath)\$(AssemblyName).dll v1 " />

eduherminio commented 6 years ago

I've just found this issue after opening #794. Any suggestions?

saxonww commented 6 years ago

I ended up putting code in my filters to check whether they had already been applied, and return early if so.

I also submitted a PR (#629) for this, but my workaround was rejected. It looks like someone else submitted a similar PR (#792) which was also closed; both apparently addressed the symptom and not the cause. @domaindrivendev said he knew the root cause and had a fix in mind, so hopefully that will be committed soon.

On Fri, Jul 6, 2018 at 3:00 AM, Eduardo Cáceres notifications@github.com wrote:

I've just found this issue after opening #794 https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/794. Any suggestions?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/541#issuecomment-402945420, or mute the thread https://github.com/notifications/unsubscribe-auth/AFDPgUhlQ-lzI8F-22Fk2IGGv2U6xGwJks5uDwsWgaJpZM4Qohcc .

domaindrivendev commented 6 years ago

@saxonww - please try 3.0.0?

saxonww commented 6 years ago

@domaindrivendev I don't have access to this project anymore, but @jrajax does and may be able to test this.

ts46235 commented 6 years ago

I'm getting this error when I run the dotnet swagger command. Its looking for dotnet-swagger.xml file when it should be looking for my assembly's xml doc file, Novek.OrderProcess.xml. If I create a dotnet-swagger.xml file and add the contents from Novek.OrderProcess.xml it works without an error.

What is my problem?

PS C:\morov\OrderProces> dotnet swagger tofile --output swagger3.json .\bin\Debug\netcoreapp2.1\Novek.OrderProcess.dll v1

Unhandled Exception: Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISwaggerProvider (DelegateActivator), Services
= [Swashbuckle.AspNetCore.Swagger.ISwaggerProvider], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> Could not find file 'C:\morov\OrderProces\bin\Debug\netcoreapp2.1\dotnet-swagger.xml'. (See inner exception for details.) ---> System.IO.FileNotFoundException: Could not find file 'C:\morov\OrderProces\bin\Debug\netcoreapp2.1\dotnet-swagger.xml'.
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
   at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
   at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
   at System.Xml.XmlTextReaderImpl.OpenUrl()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
   at System.Xml.XPath.XPathDocument..ctor(String uri, XmlSpace space)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions.<>c__DisplayClass28_0.<IncludeXmlComments>b__0()
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions.CreateSwaggerProvider(IServiceProvider serviceProvider)
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
   --- End of inner exception stack trace ---
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Execute()
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Swashbuckle.AspNetCore.Cli.Program.<>c.<Main>b__0_3(IDictionary`2 namedArgs)
   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args)
   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args)
   at Swashbuckle.AspNetCore.Cli.Program.Main(String[] args)
sorvis commented 6 years ago

Hello,

I'm testing out the CLI tool for a script that generates swagger files for an unknown number of swagger documents (named: v1, v2, v3, etc). Once it hits the end of the swagger documents and doesn't find the next one I'd like to see the command exit giving an error. It does exit giving an error:

Unhandled Exception: Swashbuckle.AspNetCore.Swagger.UnknownSwaggerDocument: Unknown Swagger document - v3
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath, String[] schemes)
   at Swashbuckle.AspNetCore.Cli.Program.<>c.<Main>b__0_3(IDictionary`2 namedArgs)
   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args)
   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args)
   at Swashbuckle.AspNetCore.Cli.Program.Main(String[] args)

The issue is though it also throws this message: image

I noticed the message is only thrown when I run it as dotnet swagger versus running it as dotnet /c/Users/sorvis/.nuget/packages/swashbuckle.aspnetcore.cli/4.0.1/lib/netcoreapp2.0/dotnet-swagger.dll which does not throw the windows error dialog. I think it just boils down to catching the exception in the application then exiting with the proper exit code so that it no longer is an un-handled exception?

sorvis commented 6 years ago

Another issue I'm seeing is when I enter an UnknownSwaggerDocument I have no idea to know what the available options really are. So I made a quick PR to add that to the error messages.

bdyer64 commented 5 years ago

I am having a problem getting XML comments into the swagger generated by the CLI command. When I load the swagger via the HTTP endpoint it all works great but when I generate the swagger via the command line no annotations from the XML comments. I see a comment above that my Startup class gets called but I don't understand how that happens given how the builder is created but I am just learning .Net Core so my knowledge is limited. Any help would be appreciated.

thomasvdb commented 5 years ago

I'm having an issue when already reading a configuration section in the ConfigureServices. Example:

var oAuthConfiguration = Configuration.GetSection("OAuthConfiguration").Get<OAuthConfiguration>();

services.AddAuthentication(options =>
{
     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
     options.Authority = oAuthConfiguration.Authority;
     options.Audience = oAuthConfiguration.Audience;
});

I get a NullReferenceException on oAuthConfiguration. If I remove this section, the generation of the swagger.json succeeds.

The section OAuthConfiguration is only configured in the appsettings.Development.json not in the appsettings.json. If I add it to appsettings.json as well, it also works.

Is this use-case supported or am I missing something?

thomasvdb commented 5 years ago

This also seems to work: ASPNETCORE_ENVIRONMENT=Development dotnet swagger tofile ...

winstonhenke-work commented 5 years ago

With version 4.0.1 of the tool I was not able to make the --basepath option work. It generated with the value of ApplicationPath from the appsettings.json file instead.

KasperHoldum commented 5 years ago

After upgrading from 5.0.0-beta to 5.0.0-RC2 we started getting the following error in jenkins:

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'System.Threading, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

 at System.Console.get_Out()

 at Swashbuckle.AspNetCore.Cli.Program.Main(String[] args)

error MSB3073: The command "dotnet swagger tofile --serializeasv2 --output "C:\jenkins\workspace\ices_abe\src\aaa\swagger.json" "C:\jenkins\workspace\ices_abe\src\aaa\bin\Release\netcoreapp2.2\aaa.dll" "v1"" exited with code 255.

If I revert back to the beta it starts working again.

thomasvdb commented 5 years ago

@KasperHoldum This issue is also logged here with some more details: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1103

Indigo744 commented 5 years ago

Hello,

We are having issue when trying to generate swagger.json:

> dotnet swagger tofile bin\Debug\net472\App.exe v1

A JSON parsing exception occurred in [App\bin\Debug\net472\App.exe]: * Line 1, Column 2 Syntax error: Malformed token
A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in 'App\bin\Debug\net472\'.
Failed to run as a self-contained app. If this should be a framework-dependent app, specify the appropriate framework in App\bin\Debug\net472\App.json.

After some research, I think it's because our projet is targeting the .net Framework (<TargetFramework>net472</TargetFramework> in csproj) and not a core framework.

What are our options to be able to generate the swagger json file from command line? Is this possible?

Thanks a lot for your help.

fiksen99 commented 5 years ago

@Indigo744 I can share our solution to this shortly

Indigo744 commented 5 years ago

@fiksen99 We went with the route proposed by @PaulDotNet (https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/541#issuecomment-359152090) and we simply call our generated Exe app with the relevant args to get the Swagger Json file.

However, I'm interested in hearing your solution.

fiksen99 commented 5 years ago

Essentially exactly what we did. Separate codepath to output the swagger when a specific arg was passed in to the exe. We also added an msbuild task as we needed the swagger as part of our build output (to input to an arm template), which I can share if interested?

On Thu, Aug 1, 2019, 10:49 PM Guillaume notifications@github.com wrote:

@fiksen99 https://github.com/fiksen99 We went with the route proposed by @PaulDotNet https://github.com/PaulDotNet (#541 (comment) https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/541#issuecomment-359152090) and we simply call our generated Exe app with the relevant args to get the Swagger Json file.

However, I'm interested in hearing your solution.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/541?email_source=notifications&email_token=AAT4R2EJG5URA7R5K4KK2VTQCPDFBA5CNFSM4EFCC4OKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD3MVROI#issuecomment-517560505, or mute the thread https://github.com/notifications/unsubscribe-auth/AAT4R2DUPNKYVGUPT7T2RSTQCPDFBANCNFSM4EFCC4OA .

Indigo744 commented 5 years ago

Thanks a lot, but I think we are ok. It works, even though I would have preferred to use the CLI tool. Thanks anyway!

woeterman94 commented 4 years ago

Does this work for .NET core 3.1?

the CLI does not seem to be compatible

chlsmith commented 4 years ago

I'm finding the same.....errors every time with 3.1