Unable to Load swagger API page, missing swagger-ui.css - c#

I am trying to add swagger to my service, but I am having some problems.
When I go to my page I get multiple calls to my webpage
/swagger/index.html -> Returns 200
/swagger/swagger-ui.css -> Returns 500
/swagger/swagger-ui-bundle.js -> Returns 500
/swagger/swagger-ui-standalone-preset.js -> Returns 500
/swagger/favicon-32x32.png -> Returns 500
/swagger/favicon-16x16.png -> Returns 500
If I go to localhost/api/myServiceName/swagger/v1/swagger.json, the file looks ok. I can see my endpoints and DTOs.
In my code I do the following:
ConfigureServices():
services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = "MyService API", Version = "v1" }); });
Configure():
app.UseSwagger();
app.UseSwaggerUI(
c =>
{
c.SwaggerEndpoint($"/api/MyService/swagger/v1/swagger.json",
"MyService API V1");
});
My project references:
Swashbuckle.AspNetCore 3.0.0
Swashbuckle.AspNetCore.Swagger 3.0.0
Swashbuckle.AspNetCore.SwaggerGen 3.0.0
Swashbuckle.AspNetCore.SwaggerUI 3.0.0
I am pretty sure something is wrong with my configuration. Any idea on what the error is?

Add a reference to Microsoft.AspNetCore.StaticFiles
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/851

Related

Swagger BaseURL empty

I am using the following Nuget in my ASP.NET Web API: https://www.nuget.org/packages/Swashbuckle/ Version: 5.6.0
I see the base URL on the Swagger for my API, shows blank. Is there a way to add base URL or remove that tag entirely?
Click here to see the image of the base URL on the swagger
I installed the Nuget package & updated the generated SwaggerConfig.cs as follows:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "API title").Contact(cc => cc.Name("team name").Email("email address"));
c.IncludeXmlComments(string.Format(#"{0}\bin\xmlName.XML", System.AppDomain.CurrentDomain.BaseDirectory));
})
.EnableSwaggerUi(c =>
{
c.DocumentTitle("document title");
c.DisableValidator();
c.DocExpansion(DocExpansion.List);
});

Swagger fails when using Microsoft.AspNetCore.OData v8.0.0-preview2

I am working on an ASP.NET Core 5 API project and I am using Microsoft.AspNetCore.OData v8.0.0-preview2.
If I use the out-of-box ASP Net Web application template, before I add OData, Swagger works just fine.
However, as soon as I add the following code;
services.AddOData(
option => option.AddModel("v1", GetV1EdmModel())
.Select()
.Expand()
.Filter()
.OrderBy()
.Count());
... to my Startup.cs --> ConfigureServices method and then try to navigate to the ../swagger endpoint the swagger page loads but displays the following error;
Failed to load API definition
Fetch error
unidentified /swapper/v1/swagger.json
Is swagger not yet supported in the Microsoft.AspNetCore.OData v8.0.0-preview2 release? Or am I missing something.
I have read through Sam Xu's blog posts; ASP.NET Core OData 8.0 Preview for .NET 5 and Routing in ASP.NET Core OData 8.0 Preview
But there was no mention of this issue.
Does anyone have a solution or a work around?
You can find the error message in the response:
System.InvalidOperationException: No media types found in 'Microsoft.AspNetCore.OData.Formatter.ODataOutputFormatter.SupportedMediaTypes'. Add at least one media type to the list of supported media types.
Try add below code after services.AddOData(...).
services.AddMvcCore(options =>
{
foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
{
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
});
And the same issue on github.

ASP.NET Core 3.1 AWS Lambda Swagger definition not working when deployed

Having the below code to configure in Startup.cs
Variables.
private const string SwaggerDocumentVersionName = "v1";
private static string SwaggerDocumentServiceName => $"Users API({SwaggerDocumentVersionName})";
ConfigureServices method.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(
SwaggerDocumentVersionName,
new OpenApiInfo
{
Title = SwaggerDocumentServiceName,
Version = $"{SwaggerDocumentVersionName}"
});
});
Configure method.
app.UseSwagger(c =>
{
c.RouteTemplate = "/swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger/ui";
c.SwaggerEndpoint($"/swagger/{SwaggerDocumentVersionName}/swagger.json", SwaggerDocumentServiceName);
});
When running locally (https://localhost:5001/swagger/ui resolved to https://localhost:5001/swagger/ui/index.html) definition is loaded correctly and everything seems fine.
Deploying the service to AWS Lambda as ASP.NET Core REST API and navigating to the URL (https://DNS_URL/API_PREFIX/swagger/ui resolved to https://DNS_URL/API_PREFIX/swagger/ui/index.html)it shows the below error loading the JSON definition.
The interesting part is that if you navigate to the JSON definition route (https://DNS_URL/API_PREFIX/swagger/v1/swagger.json) it shows the definition.
The main URL for the API you have released on lambda is https://DNS_URL/API_PREFIX/
Swagger UI needs to fetch the swagger.json file in order for it to work, and for your localhost it is working correctly since https://localhost:5001/swagger/v1/swagger.json is a valid endpoint
(*you have no prefix here)
And the version deployed to lambda is trying to fetch this swagger.json file under
https://DNS_URL/swagger/v1/swagger.json - without your API_PREFIX, thus it's returning 404, not found and swagger ui is displaying the Error message.
Quick fix, which you might apply, that I think would work:
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger/ui";
c.SwaggerEndpoint($"{env.IsDevelopment() ? "" : API_PREFIX}/swagger/{SwaggerDocumentVersionName}/swagger.json", SwaggerDocumentServiceName);
});
Where the API_PREFIX is a string starting with '/'

How to bring another project (get,post) api method to swagger api project?

I've created one API project with asp.net core in which I used swashbuckle.AspNetCore.dll to generate swagger.
It is working perfectly and going well.
Now I have another C#(.NET Standard library) in which I have created some GET, POST, DELETE, PUT method.
Need to load all of those methods to the swagger API project.
I've tried to use that separate C# library(.dll) to my project, but it didn't load to swagger.
Added this line to configuration service method at Startup.cs file:
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
In = "header", Description = "Please enter JWT with Bearer into field",
Name = "Authorization", Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
{ "Bearer", Enumerable.Empty<string>() },
});
});
Added this line to Configure method at startup.cs file:
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");
c.RoutePrefix = string.Empty;
});
It shows swagger with swagger project method. It should show both methods whether it is in a separate library or swagger project itself.
I used service stack swagger instead of swashbuckle.
It's solve my problem.
here is the solution.
https://forums.servicestack.net/t/guidance-on-enabling-oauth-2-0-in-generated-swagger-docs/3995/18

How do I specify the "scheme" element using NSwag and C#?

I'm using ASP.NET Core and NSwag to host and describe a new web service hosted in IIS with Windows Authentication.
Locally I run the web service using https, but when I deploy to a test environment the web service sits behind a load balancer with SSL-offloading. This means that even though the site appears to run under SSL in the browser, the actual binding in IIS is http. So my Swagger UI page (and swagger.json definition) describes the schemes supported as http.
I'd like the Schemes element in the Swagger.json that I use to read "https" instead of "http". Would anyone be able to help me find the property I need to set in my code to set the scheme manually?
{
x-generator: "NSwag v11.19.1.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v11.0.0.0))",
swagger: "2.0",
info: {
title: "My API title",
description: "Provides access to data.",
version: "1.0.0"
},
host: "myhostname.net",
schemes: [
"http"
],
etc...
}
Boom. Got it!
Finally found an answer on Github and the following code did the trick:
app.UseSwaggerWithApiExplorer(config =>
{
//...other code omitted...
config.PostProcess = settings =>
{
settings.Schemes.Clear();
settings.Schemes.Add(NSwag.SwaggerSchema.Https);
};
});
EDIT:
for NSwag v12 use:
app.UseSwagger(configure => configure.PostProcess = (document, _) => document.Schemes = new[] { SwaggerSchema.Https });
My project was using NSwag v13 and the below worked for me.
app.UseOpenApi(a => {
a.PostProcess = (document, _) => {
document.Schemes = new[] { OpenApiSchema.Https, OpenApiSchema.Http };
};
});
Source:
https://github.com/RicoSuter/NSwag/issues/1545

Categories

Resources