Swashbuckle(swagger) exposes other namespaces in JSON - c#

We have a public api, this is isolated in its own project(xxx.ClientApi) running asp.net (MVC).
Here we have Swashbuckle.Core version 5.6.0.
So all is good, our swagger is generated and it looks amazing, so all is good. But as soon as we jump to our Json swagger file:
/swagger/docs/v1.0
We will see alot of namespaces being exposed, and even namespaces that is not directly in the isolated project. There is nothing about these in the project and neither in the generated XML file we are basing the swagger around.
How can I control this? I cannot seem to figure this out, cannot find any posts on it, so now i will ask instead :)
This is our Config:
GlobalConfiguration
.Configuration
.EnableSwagger(c =>
{
c.RootUrl(ResolveBasePath);
c.UseFullTypeNameInSchemaIds();
c.ResolveConflictingActions(a => a.First());
c.DescribeAllEnumsAsStrings();
//SWASHBUCKLE.EXAMPLES
c.OperationFilter<ExamplesOperationFilter>();
c.OperationFilter<DescriptionOperationFilter>();
//CUSTOM
c.DocumentFilter<SwaggerDocumentFilter>();
c.OperationFilter<Consumes>();
//COMMENTS
var xmlFile = "XML documentation\\" + $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.SingleApiVersion("v1.0", "Api api")
.Contact(cc => cc
.Name("Names")
.Url("https://www.example.com")
.Email("mymail#mails.com"));
})
.EnableSwaggerUi(c =>
{
c.DisableValidator();
c.DocExpansion(DocExpansion.List);
});
EDIT #1:
#Helder Sepulveda, it could be like this:
An example could be this:
And it is probobly me who is missing something.
EDIT #2:
So i tried that, but it only removes the deeplinking of namespaces.

Related

Adding comments to endpoints w/ Swagger

I'm using Swagger / Swashbuckle for my API. I want the Swagger UI to show the method descriptions. In their documents it says:
2 - Configure Swashbuckle to incorporate the XML comments on file into the generated Swagger JSON:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new Info
{
Title = "My API - V1",
Version = "v1"
}
);
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
c.IncludeXmlComments(filePath);
}
Can someone please explain this? What I am supposed to do with this code? Do I copy and paste it somewhere? If so, where?
(.NET Framework 4.7)
EDIT:
The answer by Jawad below led me to the solution. In the original SwaggerConfig.cs file, there was this:
// If you annotate Controllers and API Types with
// Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate
// those comments into the generated docs and UI. You can enable this by providing the path to one or
// more Xml comment files.
//
//c.IncludeXmlComments(GetXmlCommentsPath());
I was unclear on how to change that last line to add my XML file. This worked:
c.IncludeXmlComments(Path.Combine(System.AppContext.BaseDirectory, "bin\\KGC.API.xml"));
I also had to add using System.IO.
The way i have done it is by updating the SwaggerConfig.cs file ..
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger("docs/{apiVersion}", c =>
{
c.SingleApiVersion("v1", "Title Of API");
c.Schemes(new List<string> { "http", "https" });
c.UseFullTypeNameInSchemaIds();
c.IncludeXmlComments(Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml"));
});
}
Last line in the code above enabled the XML comment tagging.
One other thing you have to do is,
Go to Properties of Project (not Solution)
Build / Output -> Add path to XML Documentation File.
For Reference Purposes, this was quite helpful.

Localization via resx doesn't work for non-specific resource file

I'm banging my head against a wall here and wonder if anyone has gone through this.
I have localization working on an ASP.NET Core MVC application, via resx, if I use a specific culture (in my case, es-ES).
I have a Resources\Localization.es-ES.resx file, with a dummy Localization class (for shared translation resources) and it works when the culture is es-ES. Now I want that file to work for all es cases, so I thought just renaming it to Localization.es.resx should do, but that's not picked at all.
My configuration is:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en"),
new CultureInfo("es-ES"),
new CultureInfo("es"),
};
opts.DefaultRequestCulture = new RequestCulture("en-US");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
});
/* ... */
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
And:
app.UseRequestLocalization();
I'm injecting an IStringLocalizer<Localization> and using it to translate. The query string (?culture=es or ?culture=es-ES) which I use for testing) gets picked up correctly, and again: this all works when I'm using the specific es-ES culture in the resources filename, it just doesn't when I switch to a non-specific one (just es).
This is all important because this app is specifically going to be used on other es-?? cultures and I don't want to have a copied resource file for each.
The docs specifically say (at https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.1):
Imagine your site receives a request for a "Welcome" resource using culture "fr-CA". The localization system looks for the following resources, in order, and selects the first match:
Welcome.fr-CA.resx
Welcome.fr.resx
Welcome.resx (if the NeutralResourcesLanguage is "fr-CA")
This fallback behavior doesn't seem to be working for me. Maybe I'm missing some configuration?

Swagger UI - Web API versioning when using Microsoft.AspNet.WebApi.Versioning

We are using Web API 2 on our project with Swagger. My problem is that when Microsoft.AspNet.WebApi.Versioning is applied as following:
the Swagger UI is ignoring the fact that now I have version in my API which needs to be provided.
I looked at several examples but none seem to address this issue in a satisfying manner.
How do I force Swagger to let me add the API version or just add the version number automatically to the URL?
Swagger configuration so far:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "MoovShack.ServerApi");
// If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
// In this case, you must provide a lambda that tells Swashbuckle which actions should be
// included in the docs for a given API version. Like "SingleApiVersion", each call to "Version"
// returns an "Info" builder so you can provide additional metadata per API version.
//
//c.MultipleApiVersions(
// (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
// (vc) =>
// {
// vc.Version("v2", "Swashbuckle Dummy API V2");
// vc.Version("v1", "Swashbuckle Dummy API V1");
// });
c.OperationFilter<MoovShackTokenHeaderParameter>();
})
.EnableSwaggerUi(c =>
{
// If your API has multiple versions and you've applied the MultipleApiVersions setting
// as described above, you can also enable a select box in the swagger-ui, that displays
// a discovery URL for each version. This provides a convenient way for users to browse documentation
// for different API versions.
//
//c.EnableDiscoveryUrlSelector();
});
You can see that so far MultipleApiVersions are disabled - from one good reason as it doesn't produce any results. Especially since I am not sure what "ResolveVersionSupportByRouteConstraint" should do.
I also read that "EnableDiscoveryUrlSelector" has some kind of impact but I am also not sure if that applies to my case. When I enabled it, nothing happened.
We use it like this in our project and swagger recognizes it and it looks fine
[ApiVersion( "1.0" )]
[Route("api/v{version:apiVersion}/[controller]")]
public class SomeControlelr: Controller{
[HttpGet("", Name = "Someaction"), MapToApiVersion("1.0")]
public async Task<IActionResult> SomeAction(string someParameter)

C# web api swagger integration

I have a problem to integrate swagger ui with my web api, and i don't have any idee what is the problem.
When i call in the browser the swagger, the page http://localhost:56381/swagger/ui/index is like in this screenshot
In the SwaggerConfig.cs file i have this code:
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace dummyNamespace
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c => c.SingleApiVersion("v1", "Test API"))
.EnableSwaggerUi();
}
}
}
I follow this tutorial: http://www.wmpratt.com/swagger-and-asp-net-web-api-part-1/ . But not working.
I don't now what is wrong with my configuratio.
I use .net framework 4.5.2, Web api 2.0 and Swashbuckle.5.5.3 version
Update:
When I call this url
http://localhost:56381/swagger/docs/v1
Return this image:
Update1:
After i put this code in my WebApiConfig.cs:
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
Now the http://localhost:56381/swagger/ui/index return this json:
{
"statusCode": 200
}
Any idee how to make make http://localhost:56381/swagger/ui/index return this page:
The page is from a test project.
After reading the tutorial you posted, it looks like somehow your root URL may be different than what swagger expects. From the swagger config file:
// By default, the service root url is inferred from the request used to access the docs.
// However, there may be situations (e.g. proxy and load-balanced environments) where this does not
// resolve correctly. You can workaround this by providing your own code to determine the root URL.
//
//c.RootUrl(req => GetRootUrlFromAppConfig());
If that is not the case, it could be that the swashbuckle nuget install is somehow corrupted. Try removing the nuget package and reinstalling it.

How do I generate API documentation for SignalR

Is there a way to do this?
I have swashbuckle generating content for my other APIs but I don't believe it works for SignalR.
Here's a Nuget package which can help you.
Nuget link: https://www.nuget.org/packages/SignalRSwaggerGen/
Github link: https://github.com/essencebit/SignalRSwaggerGen/wiki
First you need to decorate your SignalR hubs with attributes from SignalRSwaggerGen.Attributes namespace:
[SignalRHub]
public class SomeHub : Hub
{
}
Then you add SignalRSwaggerGen to Swagger generator:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Some API v1", Version = "v1" });
// here some other configurations maybe...
options.AddSignalRSwaggerGen();
});
For more information please refer to Github documentation.
I successfully used SigSpec for this purpose as suggested by the comment.
I had to tinker a little but it did the job.
Assuming that you're using Asp.NET Core, custom documentation can be injected at startup time.
In your Startup.ConfigureServices you should already have a Swagger section:
services.AddSwaggerGen(c =>
{
...
})
Just add a custom XML file to Swagger documentation:
services.AddSwaggerGen(c =>
{
c.IncludeXmlComments("custom_doc.xml");
})
where custom_doc.xml is a standard C# XML documentation file.

Categories