domaindrivendev / swashbuckle.aspnetcore Goto Github PK
View Code? Open in Web Editor NEWSwagger tools for documenting API's built on ASP.NET Core
License: MIT License
Swagger tools for documenting API's built on ASP.NET Core
License: MIT License
Hi,
I am using ASP.Net 5 Swagger for my API, works very good. For Authentication i want to use Oauth2 and tried to replicate the example:
services.AddSwaggerGen(c => { c.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = "http://petstore.swagger.io/api/oauth/dialog", Scopes = new Dictionary<string, string> { { "read", "read access" }, { "write", "write access" } } }); c.OperationFilter<AssignSecurityRequirements>(); });
My project.json:
"Swashbuckle.SwaggerGen": "6.0.0-rc1-final", "Swashbuckle.SwaggerUi": "6.0.0-rc1-final"
The example is working, but in my project the extension for services.AddSwaggerGen
does not accept any argument. The using statement
using Swashbuckle.SwaggerGen.Generator;
The error is that SwaggerGen does not contain the namespace Generator.
Anything broken in the nuget package?
Hi
I've created an example project showing some usages of your library. Maybe it could be of help for others.
http://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/
Thanks for the code.
Greetings Damien
First time I've used Swashbuckle, added it into an empty vnext website created from webapi template in Visual Studio 2015 (RTM), got an error whilst restoring the packages in the package manager output "Unable to locate System.Xml.XPath >= 4.0.0-beta-23110".
I found that the most recently published version on the official nuget feed is "4.0.0-beta-23019" (https://www.nuget.org/packages/System.Xml.XPath/4.0.0-beta-23019).
The quick fix is to enable the vnext nightly nuget feed "https://www.myget.org/F/aspnetvnext" in your package sources.
Considering beta5 packages have now been released, is it worth while removing the requirement on the nightly feed?
Not sure if I'm doing anything wrong. I have referenced and done the whole setup in the startup class as follows:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwagger();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvc();
app.UseIdentity();
app.UseSwagger();
app.UseSwaggerUi();
}
when I launch and navigate to the doc url e.g. http://localhost:44023/swagger/ui/index.html
there is no doc end-point listed. It basically fails to render the ui. I checked the network calls and I can see the json results coming back from the server but no ui is rendered.
I do see that there is a javascript error after the response comes back in the swagger-ui.min.js: "Invalid string length"
Steps:
Controller:
[Route("Something")]
[Produces("application/json")]
public class AnnotatedController : Controller
{
[Route("SomethingIndex")]
public IActionResult Index()
{
return View();
}
}
Call stack with extra info in it:
Swashbuckle.Swagger.SwaggerGenerator.<>c.<CreatePathItem>b__6_0(ApiDescription apiDesc) in SwaggerGenerator.cs
private PathItem CreatePathItem(IEnumerable<ApiDescription> apiDescriptions, ISchemaRegistry schemaRegistry)
{
var pathItem = new PathItem();
// Group further by http method
var perMethodGrouping = apiDescriptions
.GroupBy(apiDesc => apiDesc.HttpMethod.ToLower());
foreach (var group in perMethodGrouping)
{
var httpMethod = group.Key;
if (group.Count() > 1) throw new NotSupportedException(string.Format(
System.Linq.Lookup`2.Create[TSource](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
System.Linq.GroupedEnumerable`3.GetEnumerator()
Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry) in SwaggerGenerator.cs
var pathItem = new PathItem();
// Group further by http method
var perMethodGrouping = apiDescriptions
.GroupBy(apiDesc => apiDesc.HttpMethod.ToLower());
foreach (var group in perMethodGrouping)
{
var httpMethod = group.Key;
if (group.Count() > 1) throw new NotSupportedException(string.Format(
"Not supported by Swagger 2.0: Multiple operations with path '{0}' and method '{1}'.",
group.First().RelativePathSansQueryString(), httpMethod));
Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass4_0.<GetSwagger>b__4(IGrouping`2 group) in SwaggerGenerator.cs
throw new UnknownApiVersion(apiVersion);
var paths = GetApiDescriptionsFor(apiVersion)
.Where(apiDesc => !(_options.IgnoreObsoleteActions && apiDesc.IsObsolete()))
.OrderBy(_options.GroupNameSelector, _options.GroupNameComparer)
.GroupBy(apiDesc => apiDesc.RelativePathSansQueryString())
.ToDictionary(group => "/" + group.Key, group => CreatePathItem(group, schemaRegistry));
var swaggerDoc = new SwaggerDocument
{
Info = info,
Host = _options.Host ?? defaultHost,
BasePath = _options.BasePath ?? defaultBasePath,
System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)
Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String apiVersion, String defaultHost, String defaultBasePath, String[] defaultSchemes) in SwaggerGenerator.cs
var schemaRegistry = _schemaRegistryFactory();
var info = _options.ApiVersions.FirstOrDefault(v => v.Version == apiVersion);
if (info == null)
throw new UnknownApiVersion(apiVersion);
var paths = GetApiDescriptionsFor(apiVersion)
.Where(apiDesc => !(_options.IgnoreObsoleteActions && apiDesc.IsObsolete()))
.OrderBy(_options.GroupNameSelector, _options.GroupNameComparer)
.GroupBy(apiDesc => apiDesc.RelativePathSansQueryString())
.ToDictionary(group => "/" + group.Key, group => CreatePathItem(group, schemaRegistry));
var swaggerDoc = new SwaggerDocument
Swashbuckle.Application.SwaggerDocsMiddleware.<Invoke>d__5.MoveNext() in SwaggerDocsMIddleware.cs
if (!RequestingSwaggerDocs(httpContext.Request, out apiVersion))
{
await _next(httpContext);
return;
}
var swagger = _swaggerProvider.GetSwagger(apiVersion, null, httpContext.Request.PathBase);
RespondWithSwaggerJson(httpContext.Response, swagger);
}
private bool RequestingSwaggerDocs(HttpRequest request, out string apiVersion)
{
apiVersion = null;
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.Entity.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNet.Diagnostics.Entity.DatabaseErrorPageMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNet.Diagnostics.ErrorPageMiddleware.<Invoke>d__4.MoveNext()
Swashbuckle throws an exception when calling 'UseSwaggerGen()'.
Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
Source Assembly:
Swashbuckle.SwaggerGen
Stacktrace:
at Microsoft.Extensions.DependencyInjection.SwaggerGenServiceCollectionExtensions.GetJsonSerializerSettings(IServiceProvider serviceProvider)
at Microsoft.Extensions.DependencyInjection.SwaggerGenServiceCollectionExtensions.CreateSchemaRegistryFactory(IServiceProvider serviceProvider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.SingletonCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.SwaggerGenServiceCollectionExtensions.CreateSwaggerProvider(IServiceProvider serviceProvider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.SingletonCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.AspNet.Builder.SwaggerGenBuilderExtensions.ThrowIfServiceNotRegistered(IServiceProvider applicationServices)
at Microsoft.AspNet.Builder.SwaggerGenBuilderExtensions.UseSwaggerGen(IApplicationBuilder app, String routeTemplate)
at %.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in C:\Users..\Startup.cs:line 85
Hi,
I'm starting to play with Swashbuckle for mvc6. At the moment, the options are set on the service instead of the application. This blocks a scenario where you would want to have multiple Swashbuckle setup like this:
app.Map("/api/v1", v1App =>
{
v1App.UseMvc();
v1App.UseSwagger();
});
app.Map("/api/v2", v2App =>
{
v2App.UseMvc();
v2App.UseSwagger();
});
Which would end up with two swagger endpoints, and that's what I want. I don't really care about discoverability of all api versions in my case.
My reason for doing this is that once I'm coding v2 api, I absolutely don't want the v1 api to change. If the swagger file is part of the v1 api and we configure the service instead of the application, this would mean that I have the v1 api swagger and v2 api swagger code in one single place. Adding api distinctions in that case would become increasingly difficult to maintain.
This may be a silly question reflecting a service with odd code.
I have a simple service that returns an object using Aspnet 5 rc1. Method declaration looks like:
public ActionResult GetByProductId(int productId) => new ObjectResult(_productInfoRepository.DescribeProductByProductId(productId));
Where the respository returns a Product object.
Understandably - swagger isn't reflecting that response type. Is there an annotation I should be using to mark up the method to reflect the actual response type the client will be seeing?
Thanks
Generator doesn't respect JsonOutputFormatter settings, like camelcase property resolver
Hello!
I'm using Ahoy with a couple modifications against beta5. I say that so that you can potentially ignore this bug report since beta5 is still under development.
Anyway, when I hit my Swagger endpoint, I see the swagger json, but it's immediately followed by the ASP.NET Welcome Page content (in the same response).
app.UseSwagger("api/{apiVersion}/swagger.json");
app.UseStatusCodePages();
app.UseErrorPage();
app.UseCors(policy => policy.WithOrigins("http://polykube.io"));
app.UseMvc();
app.UseWelcomePage();
Commenting out the last line allows me to consume the swagger json as I'd expect. Not sure if I've done something wrong, if I'm using it incorrectly, or if it's simply a bug in ASP.NET5.
Ahoy does not resolve a see tag in the XML comments correctly as shown in the example below. Instead of showing the reference endpoint it displayes the string "{X:XXX.XXX.XXX.Version}" inline in the generate HTML text
/// <summary>
/// Bla. bla. use the <see cref="Version"/> method instead.
/// </summary>
Currently if there are any method parameters, the following:
Newtonsoft.Json.JsonConvert.DeserializeObject<SwaggerDocument>(swaggerString);
Fails with
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code. Additional information: Could not create an instance of type Swashbuckle.Swagger.IParameter. Type is an interface or abstract class and cannot be instantiated.`.
I worked around this by adding type tags in the constructor of SwaggerDocsMiddleware:
_swaggerSerializer = new JsonSerializer
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new SwaggerDocsContractResolver(),
TypeNameHandling = TypeNameHandling.Objects // add type tags
};
and then the following works:
JsonConvert.DeserializeObject<SwaggerDocument>(swaggerString, new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects});
Seems like a bug to me, or perhaps there's an obvious workaround I missed?
Any chance of getting an RC1-final published to nuget? Looks like the code is all there.
Runtime exception when starting up an clean ASP.NET MVC 6 site with Swashbuckle 6.0.0-beta7 installed from NuGet.
Startup.cs:
public class Startup
{
public Startup(IHostingEnvironment env)
{
}
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
services.AddSwagger();
services.ConfigureSwaggerDocument(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Swashbuckle Sample API",
Description = "A sample API for testing Swashbuckle",
TermsOfService = "Some terms ..."
});
});
services.ConfigureSwaggerSchema(options =>
{
options.DescribeAllEnumsAsStrings = true;
});
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseMvc();
// Add the following route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
app.UseSwagger();
app.UseSwaggerUi();
}
}
Looks like you changed the way we apply xml comments. The handy IncludeXmlComments
has been replaced by the less handy :
options.ModelFilter(new Swashbuckle.Swagger.XmlComments.ApplyXmlTypeComments("pathtoxmlcomments"));
options.ModelFilter(new Swashbuckle.Swagger.XmlComments.ApplyXmlActionComments("pathtoxmlcomments"")));
the issue is that you left an unintentional new()
constraint on the ModelFilter overload which takes an instance as argument. So it won't compile.
BTW, it looks like there is no easy way to configure schemes anymore. I had to write a DocumentFilter. Not sure why remove such feature.
Hello!
Can you, please, update Swashbuckle for beta5?
I use "Microsoft.AspNet.Mvc": "6.0.0-beta5-*" and my dnx version is dnx-clr-win-x86.1.0.0-beta5-11682.
Thank you.
Hi,
I'm very interested to begin to use it with asp.net 5 beta5.
Pls, can you publish as nuget package i.e. https://www.nuget.org/packages/Swashbuckle/6.0.0-beta2
Thanks!
Where to find the daily builds for beta 8?
I am using a custom JsonConverter which is configured using an JsonConverterAttribute. It gets called and used in ASP.NET 5's controllers but Ahoy does not use it so the output shown in the model schema by Ahoy's GUI is wrong.
Steps to reproduce:
A. Add a produce attribute to a controller method to inform Ahoy of the response type.
[Produces(typeof(IResource<Employment>))]
B. Add a JsonConverterAttribute to the above IResource type
[JsonConverter(typeof(ResourceJsonConverter))]
The ResourceJsonConverter now gets called by ASP.NET 5 but not by Ahoy (bug)
Hello,
I was hoping to find out when you guys plan on releasing the Beta 8?
I have a Beta 8 MVC 6 App, and I would love to get Swashbuckle installed. I tried many wasy to try and make the Beta 7 that is on Nuget now work but I keep getting this exception right when services.AddSwagger(); is called.
The Error:
System.MissingMethodException was unhandled by user code
HResult=-2146233069
Message=Method not found: 'Microsoft.Framework.DependencyInjection.IServiceCollection Microsoft.Framework.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Framework.DependencyInjection.IServiceCollection, System.Action`1<!!0>, Int32, System.String)'.
Source=Swashbuckle
StackTrace:
at Microsoft.Framework.DependencyInjection.SwaggerServiceCollectionExtensions.AddSwagger(IServiceCollection services)
at RequestIt.Api.Startup.ConfigureServices(IServiceCollection services) in C:\Users\jwuli\Dropbox\Request It Inc\Application\_Prototype\version-1\API\Working Files\RequestIt.Api\Startup.cs:line 42
InnerException:
Thanks for any help or news!
Tried running this on my Mac. Added a kestrel execution option:
"kestrel": "Microsoft.AspNet.Hosting --server Kestrel --config hosting.ini",
DSA010065:BasicApi mike.borozdin$ dnvm list
Active Version Runtime Arch OperatingSystem Alias
------ ------- ------- ---- --------------- -----
* 1.0.0-beta6 mono linux/darwin default
DSA010065:BasicApi mike.borozdin$ dnx . kestrel
Microsoft.Framework.Runtime.Roslyn.RoslynCompilationException: /Users/mike.borozdin/src/Ahoy/test/WebSites/BasicApi/Startup.cs(24,13): DNX,Version=v4.5.1 error CS0246: The type or namespace name 'IServiceCollection' could not be found (are you missing a using directive or an assembly reference?)
/Users/mike.borozdin/src/Ahoy/test/WebSites/BasicApi/Startup.cs(49,13): DNX,Version=v4.5.1 error CS0246: The type or namespace name 'IApplicationBuilder' could not be found (are you missing a using directive or an assembly reference?)
/Users/mike.borozdin/src/Ahoy/test/WebSites/BasicApi/Startup.cs(50,13): DNX,Version=v4.5.1 error CS0246: The type or namespace name 'IApplicationBuilder' could not be found (are you missing a using directive or an assembly reference?)
at Microsoft.Framework.Runtime.Roslyn.RoslynProjectReference.Load (IAssemblyLoadContext loadContext) [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Loader.ProjectAssemblyLoader.Load (System.Reflection.AssemblyName assemblyName, IAssemblyLoadContext loadContext) [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Loader.ProjectAssemblyLoader.Load (System.Reflection.AssemblyName assemblyName) [0x00000] in <filename unknown>:0
at dnx.host.LoaderContainer.Load (System.Reflection.AssemblyName assemblyName) [0x00000] in <filename unknown>:0
at dnx.host.DefaultLoadContext.LoadAssembly (System.Reflection.AssemblyName assemblyName) [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Loader.AssemblyLoaderCache.GetOrAdd (System.Reflection.AssemblyName name, System.Func`2 factory) [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Loader.LoadContext.LoadAssemblyImpl (System.Reflection.AssemblyName assemblyName) [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Loader.LoadContext.ResolveAssembly (System.Object sender, System.ResolveEventArgs args) [0x00000] in <filename unknown>:0
at System.AppDomain.DoAssemblyResolve (System.String name, System.Reflection.Assembly requestingAssembly, Boolean refonly) [0x00000] in <filename unknown>:0
at (wrapper managed-to-native) System.AppDomain:LoadAssembly (System.AppDomain,string,System.Security.Policy.Evidence,bool)
at System.AppDomain.Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity) [0x00000] in <filename unknown>:0
at (wrapper remoting-invoke-with-check) System.AppDomain:Load (System.Reflection.AssemblyName,System.Security.Policy.Evidence)
at System.AppDomain.Load (System.Reflection.AssemblyName assemblyRef) [0x00000] in <filename unknown>:0
at (wrapper remoting-invoke-with-check) System.AppDomain:Load (System.Reflection.AssemblyName)
at System.Reflection.Assembly.Load (System.Reflection.AssemblyName assemblyRef) [0x00000] in <filename unknown>:0
at Microsoft.AspNet.Hosting.Startup.StartupLoader.FindStartupType (System.String startupAssemblyName, IList`1 diagnosticMessages) [0x00000] in <filename unknown>:0
at Microsoft.AspNet.Hosting.Internal.HostingEngine.EnsureStartup () [0x00000] in <filename unknown>:0
at Microsoft.AspNet.Hosting.Internal.HostingEngine.EnsureApplicationServices () [0x00000] in <filename unknown>:0
at Microsoft.AspNet.Hosting.Internal.HostingEngine.Start () [0x00000] in <filename unknown>:0
at Microsoft.AspNet.Hosting.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0
at Microsoft.Framework.ApplicationHost.Program.ExecuteMain (Microsoft.Framework.Runtime.DefaultHost host, System.String applicationName, System.String[] args) [0x00000] in <filename unknown>:0
at Microsoft.Framework.ApplicationHost.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0
at dnx.host.Bootstrapper.RunAsync (System.Collections.Generic.List`1 args, IRuntimeEnvironment env, System.Runtime.Versioning.FrameworkName targetFramework) [0x00000] in <filename unknown>:0
Hey guys!
So I found out about Swagger a few days ago - but as I am in *.rc1-final of the MVC tooling it looks like Ahoy is my only real option for Swagger integration (outside of doing it by hand, of course).
I looked at the pull request with partial install instructions, but that is targeted as RC8, and I know there were some changes that mattered from there to rc1.
If we could get any sort of guidance, I will be happy to get it running and write a more significant bit of text on the process and contribute that back into the codebase.
Thanks for all your work in any case.
Could you update the Readme with a simple example on how to setup? Maybe a pre-release NuGet package as well 👍
The best I found documentating this was http://devmeetsbi.ghost.io/help-and-test-page-for-asp-net-web-api-asp-net-5-and-mvc-6/
Not beta-6, but then the rc1-final https://www.nuget.org/packages/Swashbuckle/6.0.0-rc1-final
Been looking into using Ahoy/SwaggerGen to document multiple APIs in an ASPNET5 application. My app has a frontend API and a backend API meant for different audiences, and their documentations should not be mixed. The APIs are exposed through urls like f.ex
I wasnt able to get the desired results without some customizations: use the interesting bits of SwaggerGen to generate the SwaggerDocument in custom controllers, bypass the SwaggerMiddlewares altogether and use swagger-ui manually.
It requires modifying or adding a new ISwaggerProvider.GetSwagger2() method to better control whats included in the SwaggerDocument. In the code below, GetSwagger2() uses the whole basePath to evaluate which methods to include, rather that just the version part.
Would it be possible to allow something like this as standard?
Regards
Anders
// MyController.cs
[HttpGet("{version}/swagger.json")]
public IActionResult Swagger(string version) {
var info = new Info();
info.Title = "My API";
info.Description = "My API documentation";
info.Version = version;
var settings = new Newtonsoft.Json.JsonSerializerSettings() {
ContractResolver = new SwaggerGenContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
var response = SwaggerProvider.GetSwagger2(info, "http://localhost:49652", "api/backend/" + version);
return Json(response, settings);
}
...
// SwaggerProvider.cs - also added in ISwaggerProvider.cs!
public SwaggerDocument GetSwagger2(
Info info,
string host = null,
string basePath = null,
string[] schemes = null) {
var schemaRegistry = _schemaRegistryFactory.Create();
// the only change is here on the top to avoid using GetApiDescriptionsFor():
var allDescriptions = _apiDescriptionsProvider.ApiDescriptionGroups.Items
.SelectMany(group => group.Items)
.Where(x => x.RelativePath.StartsWith(basePath));
var paths = allDescriptions
.Where(apiDesc => !(_options.IgnoreObsoleteActions && apiDesc.IsObsolete()))
.OrderBy(_options.GroupNameSelector, _options.GroupNameComparer)
.GroupBy(apiDesc => apiDesc.RelativePathSansQueryString())
.ToDictionary(group => "/" + group.Key, group => CreatePathItem(group, schemaRegistry));
var swaggerDoc = new SwaggerDocument {
Info = info,
Host = host,
BasePath = basePath,
Schemes = schemes,
Paths = paths,
Definitions = schemaRegistry.Definitions,
SecurityDefinitions = _options.SecurityDefinitions
};
var filterContext = new DocumentFilterContext(
_apiDescriptionsProvider.ApiDescriptionGroups,
null);
foreach (var filter in _options.DocumentFilters) {
filter.Apply(swaggerDoc, filterContext);
}
return swaggerDoc;
}
I tried to create a custom attribute (ResponseHeaderAttribute) which I look for with an OperationFilter and then add a new Header object to the operation.Responses.Headers collection (for the appropriate response), however I find there is no "name" attribute on the Header class and the Headers collection is just a List
- I had expected a Dictionary<string, Header> and assumed that the Header "name" would be the key, but it appears not. How should I add, for example an ETag header to the 201 Response from a POST?Regards,
Michael R. Gilbert
The node <response ... /> is not interpreted from the XML Comments file.
I think is a missing method to use and read Swashbuckle.Swagger.XmlComments.ApplyXmlActionComments.ResponseExpression.
Best regards,
Yann
Is there any solution in this repo for the Authorization?
Like: https://github.com/domaindrivendev/Swashbuckle#describing-securityauthorization-schemes
Thank you!
I created a new ASP.NET 5 project using Swashbuckle 6.0.0-rc1-final and configured with the following controller:
[Route("api/[controller]")]
public class SecurityController : Controller
{
[HttpPost]
[Route("Login")]
public void Login(string userName, string password)
{
}
}
Swagger renders the method correctly and provides inputs for the parameters but the Request URL sent from the UI doesnt include the parms. This same controller works correctly with a WebAPI 2.2 project.
Hi there,
This is more of a question than an issue, likely.
I'd like to include my XML documentation comments with my swagger documentation. What's the right way to do this with asp.net vnext?
I have a line like this:
c.IncludeXmlComments(".xml");
But I get a FileNotFoundException, because I'm not actually producing any build outputs.
I'm trying to build my code into a Docker image and deploy it to Rancher. Everything works great, except I don't have the nice XML documentation comments I added to my Controller and Model.
Your project is awesome. Thank you!
Ranj
if we have some param in the route, but we don't catch this parameter in action's parameters
[Route("api/users/{userId}/[controller]")]
public class OrdersController : Controller
{
[HttpGet]
public async Task<IActionResult> Get(int orderId)
{
//// action code
}
}
we will get wrong swagger data for this parameter (without type)
parameters: [
{
name: "orderId",
in: "path",
required: true,
type: "integer",
format: "int32"
},
{
name: "userId",
in: "path",
required: true
}
],
and swagger-ui 2.1.0 and greater couldn't render this file
There is no breaking changes in beta6, the package just should be recompiled with updated assemblies
Seems that Consumes attribute is ignored and that the generated json is without it. I've see a commented line (148 of DefaultSwaggerProvider.cs) that should handle consumes...
Hi,
Is it possible to generate a swagger file from a dnx console app? I'm looking into the possibility of adding a second command to our asp.net app to generate the file so that we can then generate a client for the api as part of our build process.
Thanks
Just yesterday I've tried this nice little tool and unfortunately I've got a NRE.
the controller code looks like this:
public class Item
{
/// <summary>
/// or that
/// </summary>
public int Id;
/// <summary>
/// or this
/// </summary>
public string Name;
}
/// <summary>
/// Some summary
/// </summary>
///
[Route("api/[Controller]")]
[Produces("application/json", "text/json")]
public class ItemsController : Controller
{
/// <summary>
/// Return all items
/// </summary>
public static List<Item> Items = new List<Item>
{
new Item { Id = 1, Name = "First Test Item" },
new Item { Id = 2, Name = "Second Test Item" },
};
/// <summary>
/// Get all items
/// </summary>
/// <remarks>This will return all items</remarks>
/// <returns>RETURN</returns>
[HttpGet]
public IEnumerable<Item> Get()
{
return Items;
}
/// <summary>
/// Get Item by Id
/// </summary>
/// <param name="id">A var</param>
/// <param name="dummy">just a dummy var</param>
/// <returns>RETURN</returns>
[HttpGet("itemId")]
public Item Get([FromQuery]int id, int dummy)
{
return Items.FirstOrDefault(item => item.Id == id);
}
}
Using xml comments this will result in a Null reference Exception in XmlCommentsModelFilter.ApplyPropertyComments @ line 43
The problem is that memberInfo is null.
The problem seems to be with this part of the code above:
public class Item
{
/// <summary>
/// or that
/// </summary>
public int Id;
/// <summary>
/// or this
/// </summary>
public string Name;
}
I fixed it by adding
if (memberInfo == null) return;
But I don't know if this is actually the proper way in doing it.
By the way: Will there be also a .Net4.5.1 version of Swashbuckle? :)
We plan to use it in MediaPortal2 and this is based on .Net4.5.1.
Currently ConfigureSwaggerDocument and ConfigureSwaggerSchema must be done in Setup.ConfigureServices of the client web project. At this stage the client knows nothing about the execution environment so it need to hardcode a full path the the documentation XML XmlComments file. Not nice!
It would be better if these can be done later in Setup.Configure where it is possible to use dependency injection to get hold of IApplicationEnvironment which allows for calculating where the XML XmlComments file is located relative to the ApplicationBasePath.
The previous WebAPI based Swashbuckle supported a method to add your own custom javascript and css files (as embedded resources) to the Swagger UI. How does one do that with the ASP.NET 5 version?
Hallo,
your Namespace for the AddSwagger Extension is wrong for RC1. It was renamed by Microsoft a few weeks ago. Microsoft.Framework.* is now Microsoft.Extensions.*
namespace Microsoft.Framework.DependencyInjection
HAS TO BE
namespace Microsoft.Extensions.DependencyInjection
{
public static class SwaggerServiceCollectionExtensions
{
public static void AddSwagger(this IServiceCollection services)
{
Is there a way to inject a custom stylesheet like in Swashbuckle for WebAPI?
.EnableSwaggerUi(x =>
{
x.InjectStylesheet(typeof(AppHost).Assembly, "MyProject.Api.Resources.Swagger.UiCustomization.css");
});
I prefer the Produces attribute which is standard ASP.NET (in vNext) to describe return types rather then swagger-specific SwaggerResponse attribute. Unfortunately, XML comments to specify return types is not supported so currently I have to specify a SwaggerResponse for return types. However if I specify SwaggerResponse then I have to specify a type parameter as well or it's default will overwrite the type in the Produces attribute with an empty-type. This means I have to specify the type multiple times as in the example below which I think is bad practice. I would like to remove the type specifier on the SwaggerResponse if I have a Produces attribute (p.s. and for XML comments to be supported as well - see issue #24)
[Produces(typeof(Employee))]
[SwaggerResponse(System.Net.HttpStatusCode.OK, Type=typeof(Employee))]
[SwaggerResponse(System.Net.HttpStatusCode.NotFound)]
I am working on a sample application, I have swagger running fine on windows using 1.0.0-beta7 coreclr x64, by running dnu web command. But using the same code running on Ubuntu 14.04 but run 'dnx kestrel', also same 1.0.0-beta7 coreclr x64, I am not able to have correct swagger ui rendered. To be specific: I got 500 for a static file:Swagger-ui.js
index.html 200 document Other 4.6 KB 200 ms
reset.css 304 stylesheet index.html:9 201 B 89 ms
screen.css 304 stylesheet index.html:10 201 B 90 ms
typography.css 304 stylesheet index.html:8 201 B 89 ms
jquery-1.8.0.min.js 304 script index.html:13 215 B 85 ms
jquery.slideto.min.js 304 script index.html:14 215 B 85 ms
jquery.wiggle.min.js 304 script index.html:15 215 B 86 ms
handlebars-2.0.0.js 304 script index.html:17 215 B 89 ms
underscore-min.js 304 script index.html:18 215 B 98 ms
swagger-ui.js 500 script index.html:20 0 B 193 ms
backbone-min.js 304 script index.html:19 215 B 98 ms
jquery.ba-bbq.min.js 304 script index.html:16 215 B 96 ms
marked.js 304 script index.html:22 215 B 97 ms
highlight.7.3.pack.js 304 script index.html:21 215 B 96 ms
swagger-oauth.js 304 script index.html:23 215 B 97 ms
print.css 304 stylesheet index.html:12 201 B 15 ms
logo_small.png 304 png jquery-1.8.0.min.js:2 202 B 4 ms
droid-sans-v6-latin-700.woff2 304 font jquery-1.8.0.min.js:2 215 B 4 ms
favicon-16x16.png 200 png Other 858 B 11 ms
favicon-32x32.png 304 png Other 202 B 3 ms
These files shouldn't be checked in. They are readily built on demand and inflate the repo.
Hello,
I tried adding the package via nuget but I could not access the extension methods for Swagger
"Swashbuckle": "6.0.0-beta1"
So I decided to clone the repo locally the add it to my solution as a project and to my vNext project as a dependency. The solution built and the vNext website run. Unfortunately, I cannot access /swagger/ui neither can I access /swagger/v1/swagger.json. Here is my setup
Inside the ConfigureServices method
// Add swagger documentation
services.AddSwagger(s => {
s.SwaggerGeneratorOptions(c => {
s.SwaggerGeneratorOptions.Schemes = new[] { "http", "https" };
s.SwaggerGeneratorOptions.SingleApiVersion(new Swashbuckle.Swagger.Info {
Version = "v1",
Title = "My vNext Api",
Description = "some placeholder for description",
TermsOfService = "some terms if need be"
});
s.SchemaGeneratorOptions.DescribeAllEnumsAsStrings = true;
});
Inside the Configure method
// Add Swagger Docs
app.UseSwagger();
app.UseSwaggerUi();
I put breakpoints to ensure that they initialized and yes they did. Any guidance?
We should add support for building CoreCLR (dnxcore50).
I was able to prototype it pretty easily by adding this to project.json:
"frameworks": {
"dnx451": { },
"dnxcore50": {
"dependencies": {
"System.Xml.XPath": "4.0.0-beta-*"
}
}
}
The only extra dependency needed was xpath. Consider doing the same for the tests.
Doing a dnu restore
dnu build
will build for both flavors.
First, thanks for getting the beta8 build out. I've gotten it integrated successfully, except for one glitch.
The Swagger UI loads but my Swagger JSON won't validate properly.
I get this error:
[{"level":"error","domain":"validation","keyword":"pattern","message":"ECMA 262 regex "^/" does not match input string ""","schema":{"loadingURI":"#","pointer":"/properties/basePath"},"instance":{"pointer":"/basePath"}}]
My guess is that it's from having a null basePath?
I'd actually prefer to have a basePath of /api/v1, and have the rest of the paths be relative.
Is this configurable via Swashbuckle?
"swagger": "2.0",
"info": {
"version": "v1",
"title": "API V1"
},
"basePath": "",
"paths": {
"/api/v1/vendors/{vendorId}/applications": {
On VS2015 (14.0.23107.0) download Zip of Ahoy, run project on Win10 VM on azure,
Open in Project Spartan (IE vNext)
http://localhost:1417/swagger/ui/index.html
does not serve any pages but does on Chrome
How do you disable the validator in this new API? You could do this in the old API:
config.EnableSwagger().EnableSwaggerUi(c => c.DisableValidator());
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.