Swagger not found in .NET 5.0 - swagger

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.

Related

SwaggerUI causes Index.html startup side effect on IIS express in Blazor App

I created a new Blazor Server project and added SwaggerUI and now the application searches for index.html as the start up object when I debug.
Interesting, I isolated the offending code to the routeprefix=""
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1.3");
c.DocExpansion(DocExpansion.None);
// c.RoutePrefix = "";
});
I run it once with the routeprefix ="" and the startup is set to index.html. Even when I comment it out, it still searches for the index.html page.
I did a few test and found that no relevant code was changed from the working and the non working.
I deployed the code to IIS and it seemed to work so I am guessing it maybe something to do with IIS express. I checked the configurations but did not find any think useful.
The code is the standard weather forecast test project created by default.
Here is the main program.
using BlazorAppIndexTest.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddControllers();
builder.Services.AddSingleton<WeatherForecastService>();
//first line added
builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My Service", Version = "v1" }); });
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
//second line added
app.UseSwagger();
//third line added
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1.3");
c.DocExpansion(DocExpansion.None);
// c.RoutePrefix = "";
});
app.Run();
Anyone have any ideas of how to fix this or force the application to start with razor page.
AS usual, I found the answer after I posted the question.
Clearing the browser cache worked. I swear I tried that before.

Be sure that the Startup.cs for your application is calling AddSwaggerGen from within ConfigureServices in order to generate swagger file

I'm getting the above error message when publishing my .NET 6 API project to Azure API Management Service.
On analysis, I understood the reason for the issue is, while configuring services (for DI) in 'Program.cs', we are trying to fetch an Environment variable, which returns null and an exception is thrown. Somehow, this prevents creating the swagger.json file.
Two things that I'm trying to understand are,
Fetching the environment variable using "Environment.GetEnvironmentVariable()" is not fetching the value in 'Program.cs', but the same works in controller action method.
If I comment out everything related to swagger, this issue is not occurring.
In the Publish Window, under 'Service Dependencies', I have configured my APIM resource details to deploy/update the APIs in the APIM directly.
Below is a sample code screeshot which replicates the issue.
Please share your thoughts.
Thanks!
Initially even I got the same error with the given code.
The issue is at getting the Environment Variable.
To get the Key Value(Environment Variable) from Azure App settings, use the below line of code.
var key1 = app.Configuration.GetValue<String>("KEY");
My Azure App Setting:
Change app.UseSwaggerUI to
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = string.Empty;
});
My Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (string.IsNullOrEmpty(app.Configuration.GetValue<String>("KEY")))
throw new Exception("Error");
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.RoutePrefix = string.Empty;
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
My appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"KEY": "Your Connection String"
}
Make sure you have installed the Swashbuckle.AspNetCore latest package.
.csproj file
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
Output:

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: change api route in Swagger UI

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: /

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