Swagger: change api route in Swagger UI - swagger

I have two kubernetes services deployed on a AKS, they receive traffic from a Nginx Ingress Controller. The endpoints for these two services are https:<dns>/service1and https:<dns>/service2. Now I want to set up Swagger for each services. Below is how I set up Swagger UI for one of the services.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/service1/swagger/v1/swagger.json", "API V1");
});
With this configuration, I can get access to swagger by https:<dns>/service1/swagger.
Now the problem is, in Swagger UI, when I want to test the api by clicking the "Try it out" button then Excute button, the url that Swagger UI access is https:<dns>/api/v1/contoller instead of https:<dns>/service1/api/v1/contoller. Which means that Swagger UI is not aware of the existance of path /service1/. I found several related questions like this one How to change base url of Swagger in ASP.NET core
. But they are not the solution for my problem. My guess is I need to set a base path for Swagger. If anyone could tell me how to configure base path for Swagger in ASP.NET core 2.0, it would be much appreciated.

Change this:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/service1/swagger/v1/swagger.json", "API V1");
});
to this:
For dotnet core 2.x
app.UseSwagger(c =>
{
#if !DEBUG
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = "/service1");
#endif
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("./swagger/v1/swagger.json", "API V1");
});
For dotnet core 3.x (Swashbuckle 5.x prerelease+)
app.UseSwagger(c =>
{
#if !DEBUG
c.RouteTemplate = "swagger/{documentName}/swagger.json";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Servers = new System.Collections.Generic.List<OpenApiServer>
{
new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/service1" }
});
#endif
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("./swagger/v1/swagger.json", "API V1");
});
#if !DEBUG ... #endif is necessary for accessing the swagger ui while debugging in local machine.
Note: I'm assuming "/service1" is the same value as in your values.yaml file of your helm chart. (see below)
...
ingress:
enabled: true
annotations: {
kubernetes.io/ingress.class: "nginx",
nginx.ingress.kubernetes.io/rewrite-target: /$1
}
path: /service1/?(.*)
hosts:
- your-aks-subdomain.your-azure-region.cloudapp.azure.com
tls: []
# - secretName: chart-example-tls
# hosts:
# - chart-example.local
hpa:
...

Please en your public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
use after this:
app.UseSwaggerUI(c=>
{
c.SwaggerEndpoint("/service1/swagger/v1/swagger.json", "Giftaway API V1");
This option
c.RoutePrefix = "service1";
this will get you https:<dns>/service1/api/v1/controller

Based on https://github.com/apigee-127/swagger-tools/issues/342#issuecomment-391940961 and https://github.com/springfox/springfox/pull/1217 maybe you could try setting the X-forwarded-prefix in your ingress rule like https://github.com/kubernetes/ingress-nginx/pull/1805#issuecomment-366896998

In your ingress don't use this annotation
nginx.ingress.kubernetes.io/rewrite-target: /

Related

Swagger not found in .NET 5.0

I have a .NET 5.0 API project setup with API versioning and swagger. This is my ConfigureServices method:
services.AddSwaggerGen(c => {
// Set the swagger doc stub
c.SwaggerDoc("v1", new OpenApiInfo {
Version = "v1",
Title = "API"
});
// Set the comments path for the Swagger JSON and UI.
string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
and this is my Configure method:
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
c.RoutePrefix = string.Empty;
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
The problem I'm having is that, when I run the project locally, the /swagger endpoint returns a 404. However, navigating to /swagger/v1/swagger.json returns the swagger JSON document. I've seen similar problems here, here and here, but none of the solutions presented here fixed the problem, mainly because I'm not using IIS. I've also looked at Microsoft's official documentation, here, but I haven't noticed any differences. What am I doing wrong here?
I was able to fix the issue by looking at here. I'm not quite sure why, but removing the line c.RoutePrefix = string.Empty; from the Configure method fixed the issue.

Uncaught ReferenceError: SwaggerUIBundle is not defined at window.onload

In my localhost, my swagger UI working well. localhost:3030/documentation
This UI was working on the server also but from today on the server it is not working https://digitalpathshalabd.com/documentation
Errors
I faced the same "SwaggerUIBundle is not defined" with a blank page. Also the problem only on server and not local. And it also had worked in the past.
Then when I ctrl+f5 the local swagger page, it then also appeared local.
For us it appeared the Configuration order was swapped.
For me the fix was moving app.UseRouting() after the swagger init
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Procedure Service V1");
c.RoutePrefix = "";
});
app.UseRouting();
I am using org.springdoc:springdoc-openapi-ui:1.6.9 version and was facing this problem.
I checked https://www.npmjs.com/package/swagger-ui and added maven dependency for a lower swagger-ui version 3.0.21
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>3.0.21</version>
</dependency>
I found that the "swagger-ui/index.html" does not reference "swagger-initializer.js" , instead its source code is present in index.html itself (this the boiler-plate referring to pet store)
So in my Spring boot classpath resources/public folder, I copied the older swagger dist index.html file (which has the initializer code) and did the following changes
Changed the url part to point to my api-docs url. (e.g. /v3/api-docs)
Added "swagger-ui" to the src references, so that the swagger bundles/js will be called successfully from my index.html
<script charset="UTF-8" src="./swagger-ui/swagger-ui-bundle.js"></script>
<script charset="UTF-8" src="./swagger-ui/swagger-ui-standalone-preset.js"> </script>
When I accessed index.html - http://{server}:{port}/index.html- I could access my local Open API doc.
Check your swagger middleware configured correctly?
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddControllers();
}
This adds the Swagger generator to the services collection.
In the Configure() method, let’s enable the middleware for serving the generated JSON document and the Swagger UI:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}

Facing issue with configure method in .Net core application

I have developed .Net core API project and deployed on the server.
I added it as site on IIS(remote windows server)and tried to browse the application.
The application is not working properly facing issue at Configure method
Here is my configure method in >net core
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var appName = "";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api V1");
});
}
Please let me know how can to add swagger endpoint.
I guess you directly publish your web application to a nested site in the default website on IIS.
So the "/swagger/v1/swagger.json" root path will become localhost/swagger/v1/swagger.json not localhost/yourwebsitename/swagger/v1/swagger.json.
To solve this issue, I suggest you could try to modify the SwaggerEndpoint path as this `c.SwaggerEndpoint("../swagger/v1/swagger.json", "Api V1");.
More details, you could refer to below startup.cs
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json", "Api V1");
});
`

Swagger breaks when adding an API Controller to my Host Project in aspnetboilerplate

I downloaded a new .Net Core MVC project template from https://aspnetboilerplate.com/Templates, setup everything (database and restored nuget packages) and ran the Host application. All good as I get the Swagger UI going and can see all the standard services.
I then proceeded to create a simple API controller in the Host application:
[Route("api/[controller]")]
[ApiController]
public class FooBarController : MyAppControllerBase
{
public string HelloWorld()
{
return"Hello, World!";
}
}
And then Swagger fails to load the API definition:
Fetch error
Internal Server Error http://localhost:21021/swagger/v1/swagger.json
If I remove the Route and ApiController attributes, Swagger works again, but my new controller is not displayed. I can access it by going to http://localhost:21021/foobar/helloworld which is probably fine, but I'd like it to show up in Swagger UI.
Am I missing something?
This is how you should configure your Swagger in your "Configure(IApplicationBuilder app, IHostingEnvironment env)" method.
#region Swagger COnfiguration
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("swagger/v1/swagger.json", "Your class name");
c.RoutePrefix = string.Empty;
});
#endregion
And here will be your configureServices settings for swagger.
services.AddSwaggerGen(config =>
{
config.SwaggerDoc("v1", new Info
{
Title = "Title Here",
Version = "v1"
});
});

Not able to Inject Javascript in Swagger

I get a 404 for a JavaScript file that I am trying to inject in my swagger. Following is my swagger config
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "A title for your API");
})
.EnableSwaggerUi(c =>
{
c.InjectJavaScript(thisAssembly,"MyApi.Api.SwaggerExtensions.inject.js");
});
For inject.js build action is set to embedded resource and logical path is correct as my project name is MyApi.Api and the file is in a folder within the project named SwaggerExtensions
When using custom resources the resource name should contain the default namespace of your project as described here. In your case the configuration should be:
c.InjectJavaScript(thisAssembly, "AcctMgmt.SwaggerExtensions.inject.js")
I spent a lot of time trying to figure out that a method with the same name has a different behavior. The config in Startup.Configure expects a relative path from wwwroot:
public void Configure(IApplicationBuilder app) {
//
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Salon API v1");
c.InjectJavascript("/SwaggerExtension.js");
});
}
Get started with Swashbuckle and ASP.NET Core

Resources