Using XmlComment for swagger api helper page - c#

I got error when try to config swagger for my new start ASP.NET Core api project. It work perfectly on local host : the comment work good with xml comment. But when I publish it to azure host, it doesn't work.
Then I tried to find out the way is comment the config code which add xml comment to swagger :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMvcCore().AddApiExplorer();
services.AddLogging();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = " API Helper Page",
Description = "A simple start ASP.NET Core Web API/ MBAAS",
TermsOfService = "None",
Contact = new Contact { Name = "Nguyễn Bá Nguyên", Email = "", Url = "https://github.com/hello/" },
License = new License { Name = "Under Construction...", Url = " " }
});
// Set the comments path for the swagger json and ui.
// only working on local, need to be fixed
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, ".xml");
c.IncludeXmlComments(xmlPath);
});
}
to get publish to azure without bug I commented the last
//var basePath = PlatformServices.Default.Application.ApplicationBasePath;
//var xmlPath = Path.Combine(basePath, ".xml");
//c.IncludeXmlComments(xmlPath
);
and azure host worked but swagger can't use xml comment :(
So is there any way to config swagger to use xml comment for azure host?

I faced the same issue using swagger xml comments with .NET core on Azure API App. After I set the stdoutLogEnabled flag to true within the web.config I figured out that the XML file is missing. After I uploaded the xml file manually to the API it worked.
To upload the XML file you can use the Kudu service (either type <yourapi>.scm.azurewebsites.net or within the app in the Azure portal -> Development Tools -> Advanced Tools). Then click on Debug console, navigate to your site and upload the xml file:

Related

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

Store Swagger UI Tokens Permanently after Browser Refresh or Computer Restart

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)

Swagger Ui not load static files on asp.net mvc

i'm using swagger ui in my asp.net mvc
Swashbuckle v 5.6
asp.net v 4.8
on local machine everythink working successfully but unfortunately after deploy website to cloud, swagger not load static content, but wen i navigate to these resources using chrome it's loadded successfully
i config swagger using:
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.Schemes(new[] { "http", "https" });
c.IgnoreObsoleteActions();
c.SingleApiVersion("v1", "Console - API");
c.ApiKey("auth")
.Description("API Key Authentication")
.Name("auth")
.In("header");
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
c.IncludeXmlComments(String.Format(#"{0}\bin\docs.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.UseFullTypeNameInSchemaIds();
})
.EnableSwaggerUi(c =>
{
c.DocumentTitle("Console - API");
c.EnableApiKeySupport("auth", "header");
c.InjectJavaScript(thisAssembly, "Console.API.Assets.Swagger.SwashbuckleCustomAuth.js");
c.InjectStylesheet(thisAssembly, "Console.API.Assets.Swagger.SwashbuckleCustomStyle.css");
});
}
Do i miss any thing? dose https effects swagger load static files?
pss: i don't think this issue related to iis because i have placed a static file in root folder of the website and i was able to load it
The IIS was block simultaneous requests, and the solution was by increment maximum concurrent connections in site advance settings in IIS

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