I have a list of APIs and when one of the APIs is selected, I want to display the Swagger page for that API only.
In the Program.cs file
if (app.Environment.IsDevelopment())
{
app.UseSwagger(options =>
{
});
app.UseSwaggerUI(options =>
{
});
}
and there is a link to the project here.
Related
I have a blazor wasm application running on a subpath Apps/Genesis/
The problem is some DLL's are not being found:
The request is:
https://localhost:5001/Apps/Genesis/Apps/Genesis/_framework/Blazored.LocalStorage.dll
The request should be:
https://localhost:5001/Apps/Genesis/_framework/Blazored.LocalStorage.dll
app.MapWhen(
context =>
{
return context.Request.Path.StartsWithSegments("/Apps/Genesis");
},
genesis =>
{
// Define blazor files
genesis.UseBlazorFrameworkFiles("/Apps/Genesis");
// Access static files (Ex.: images, dll's) - Used twice because it's on the microsoft docs example
genesis.UseStaticFiles();
genesis.UseStaticFiles("/Apps/Genesis");
// Apply routing for UseEndpoints
genesis.UseRouting();
// Especify Routes
genesis.UseEndpoints(
endpoints =>
{
endpoints.MapControllers();
endpoints.MapFallbackToFile("Apps/Genesis/{{*path:nonfile}}", "Apps/Genesis/index.html");
});
});
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 '/'
Is there any method to hardcode tokens into Swagger UI permanently in Local computer or Dev Environment ?
We are testing Net Core Apis and also running them through Angular 8: developing, rebuilding, writing code, testing Swagger APIs over 100 times a day each.
Looking for way, to store token below, so don't have to keep Reentering.
Can be very cumbersome, consuming time, as minutes add up.
Maybe we can read a token from external file in developer desktop. Token stays so even after computer restarts, developers are not required to reenter tokens. Perhaps in appsettings.json or any file?
Or anyway to inject code with Net Core Visual Studio Environment, that does not expose token in Source control?
Answer should run all Swagger UI and APIs ran from Angular environment,
Only in QA and Production will require entry of token
Using Angular and Net Core 2.0 C#,
I managed to do it in ASP.NET Core 5 by adding this line to startup.cs, Configure method
app.UseSwaggerUI(c =>
{
c.ConfigObject.AdditionalItems.Add("persistAuthorization","true");
});
I found this by reading this docs
And here
Adapting my other answer to your case, your setup can look like follows:
wwwroot/swashbuckle.html
<!-- your standard HTML here, nothing special -->
<script>
// some boilerplate initialisation
// Begin Swagger UI call region
configObject.onComplete = () => {
// this is the important bit, see documentation
ui.preauthorizeApiKey('api key', 'HARDCODE YOUR KEY HERE' );// key name must match the one you defined in AddSecurityDefinition method in Startup.cs
}
const ui = SwaggerUIBundle(configObject);
window.ui = ui
}
</script>
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
.........
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
c.AddSecurityDefinition("api key", new ApiKeyScheme() // key name must match the one you supply to preauthorizeApiKey call in JS
{
Description = "Authorization query string expects API key",
In = "query",
Name = "authorization",
Type = "apiKey"
});
var requirements = new Dictionary<string, IEnumerable<string>> {
{ "api key", new List<string>().AsEnumerable() }
};
c.AddSecurityRequirement(requirements);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
if (env.IsDevelopment()) // override swashbuckle index page only if in development env
{
c.IndexStream = () => File.OpenRead("wwwroot/swashbuckle.html"); // this is the important bit. see documentation https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md
}
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); // very standard Swashbuckle init
});
app.UseMvc();
}
There are different ways to deliver your key to swagger, hard-coding might be not the best, but it should hopefully get you started.
Since you indicate you only want this functionality for development environment I opted to only serve the modified file if (env.IsDevelopment()), which you, again, can tweak to your needs
you add this functionality through swashbuckle
https://cpratt.co/customizing-swagger-ui-in-asp-net-core/
Enable bearer token in Swashbuckle (Swagger document)
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
I am using ASP.NET Boilerplate v2.0.1 with .NET Core and Angular 2 project template.
I have multiple modules in my project that are currently served using same API endpoint. Please note, in the future I will have separate API endpoint for an individual module.
As the API endpoint is same for every module, the service proxy which is generated through NSwag will have all the modules' services.
I am having a requirement to have proxy generated based on an individual module, so for this, I thought of accomplishing using API versioning. So instead of v1, v2 etc., I will append the module name.
I have the following code:
Configuration.Modules.AbpAspNetCore()
.CreateControllersForAppServices(
typeof(Module).GetAssembly(),
"modulename"
);
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("module1", new Info { Title = "Module 1", Version = "module1" });
options.SwaggerDoc("module2", new Info { Title = "Module 2", Version = "module2" });
}
app.UseSwagger(options =>
{
options.RouteTemplate = "swagger/{documentName}/swagger.json";
});
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/module1/swagger.json", "Module 1");
options.SwaggerEndpoint("/swagger/module2/swagger.json", "Module 2");
});
This way, I am able to generate two endpoints as follows:
http://localhost:5000/swagger/module1/swagger.json
http://localhost:5000/swagger/module2/swagger.json
But both are having all the modules' information.
Please correct me or suggest a way to achieve the functionality.
It looks like you are using swashbuckle and not NSwag to generate your swagger docs. There are multiple ways to separate your docs by version, see swashbuckle documentation https://github.com/domaindrivendev/Swashbuckle.AspNetCore. The default method is to use your startup configs that you have above and decorate your methods with the corresponding ApiExplorer group name. The group name needs to match the first argument specified in the swaggerdoc config.
[ApiExplorerSettings(GroupName = "module1")] //Module 1 Method
You are also missing an 'e' in module for the second swagger endpoint.
see example: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/4bbf5cacd6ad0817b9015d699c559fd5c1cedf0d/test/WebSites/MultipleVersions/Startup.cs
To add multiple source edit the SwaggerUIOptions.
For example:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("http://<ip1>:<port>/swagger/v1/swagger.json", "ServiceName1");
c.SwaggerEndpoint("http://<ip2>:<port>/swagger/v1/swagger.json", "ServiceName2");
});