Swagger is stripping the website name off the Base URL - swagger

I'm using swagger but when I host my webapi in IIS, swagger is stripping the website name off. The website is a virtual directory/application in IIS called LotsWebApi.
When I hit this url: http://localhost/LotsWebApi/swagger/ui/index.html
I get "Can't read swagger JSON from http://localhost/swagger/v1/swagger.json"
You can see that it is stripping off the 'LotsWebApi'.
My register swagger code looks like this...
private static void RegisterSwagger(IServiceCollection services)
{
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "LOTS Web API",
Description = "API for LOTS Web"
});
});
services.AddSwaggerGen();
}

Related

Where to set API host schema in Swashbuckle?

I'm trying to figure out how to fix an issue I have going on with Swagger displaying on our STAGE and PROD servers. I believe my issue is the fact that we have Load Balancer that uses HTTPS to get to but once you get there all the sites are served over HTTP. I believe that is the reason I'm getting
Can't read from server. It may not have the appropriate access-control-origin settings.
So I found the following on Swagger and I'm thinking I just need to set my Schema to HTTP but I'm not 100% sure where to make this change? Do I add it to the SwaggerConfig.cs file?
https://swagger.io/docs/specification/2-0/api-host-and-base-path/
This is what I have in my SwaggerConfig.cs file:
public class SwaggerConfig
{
//public static void Register(HttpConfiguration config)
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.ApiKey("Api-Token")
.Description("API Key for accessing secure APIs")
.Name("Api-Token")
.In("header");
c.SingleApiVersion("v1", "WorkdayAPI");
c.IncludeXmlComments(string.Format(#"{0}\bin\WorkdayApi.XML",
System.AppDomain.CurrentDomain.BaseDirectory));
// If you want the output Swagger docs to be indented properly, enable the "PrettyPrint" option.
c.PrettyPrint();
})
.EnableSwaggerUi(c =>
{
// If your API supports ApiKey, you can override the default values.
// "apiKeyIn" can either be "query" or "header
c.EnableApiKeySupport("Api-Token", "header");
});
}
}

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"
});
});

Issue Using Custom Index.Html in Swagger / Swashbuckle for .NET Core

I am having difficulty using a custom index.html and other assets with swashbuckle. Swashbuckle/Swagger do not seem to recognizing or using them at all. I do have app.UseDefaultFiles() and app.UseStaticFiles() set. I am trying to understand what I am doing incorrectly.
I have attempted to set up my configuration somewhat similar to what is defined on the Microsoft article without success. (https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio)
I am presently using the files from the dist folder referenced in the article (https://github.com/swagger-api/swagger-ui/tree/2.x/dist) along with the custom css file provided.
My index.html file is located under /wwwroot/swagger/ui
The custom css file is located under /wwwroot/swagger/ui/css (as custom.css)
Here is my Startup.cs class.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options =>
{
// Swagger - Format JSON
options.SerializerSettings.Formatting = Formatting.Indented;
});
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.DescribeAllEnumsAsStrings();
c.DescribeStringEnumsInCamelCase();
// c.DescribeAllParametersInCamelCase();
c.SwaggerDoc("v1",
new Info
{
Title = "My Web API - v1",
Version = "v1",
Description = "New and improved version. A simple example ASP.NET Core Web API. "
}
);
c.SwaggerDoc("v2",
new Info
{
Title = "My Web API - v2",
Version = "v2",
Description = "New and improved version. A simple example ASP.NET Core Web API. "
}
);
// Set the comments path for the Swagger JSON and UI.
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "ApiTest.xml");
c.IncludeXmlComments(xmlPath);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
string swaggerUIFilesPath = env.WebRootPath + "\\swagger\\ui";
if (!string.IsNullOrEmpty(swaggerUIFilesPath))
{
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(swaggerUIFilesPath),
RequestPath = new PathString("/api-docs"),
});
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
{
c.RouteTemplate = "api-docs/{documentName}/swagger.json";
});
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
//c.ShowJsonEditor();
c.RoutePrefix = "api-docs";
c.SwaggerEndpoint("/api-docs/v1/swagger.json", "My Web API - V1 ");
c.SwaggerEndpoint("/api-docs/v2/swagger.json", "My Web API - V2 ");
c.DocumentTitle("My Web API");
});
app.UseMvc();
}
}
My ultimate objective is to be able to use something like the slate style theme available here (https://github.com/omnifone/slate-swagger-ui). For right now, I am just trying to get Swashbuckle/Swagger to use the customized files referenced in the Microsoft documentation before trying to make the other files work.
I really do NOT want to try and convert my assets to embedded resources--since there will many of them. I just want to reference a normal index.html file and be able to use all of its referenced files.
What am I doing wrong?
Relevant Software Versions
.Net Core Version: 2.0.3
Swashbuckle.AspNetCore: 1.2.0
Windows 10 Enterprise Build 1703
Visual Studio 2017 Enterprise 15.5.2
Here is the minimum action I found to be necessary to replace SwashBuckle's index.html in a .NET Core project:
Get a copy of the original index.html from here: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html
Place that copy in some sub-folder of your project.
The file may have a different name, I chose:
\Resources\Swagger_Custom_index.html
Right-click that file in Solution Explorer, select 'Properties', select 'Configuration Properties' in left pane. Under 'Advanced' in right pane find entry 'Build Action' and set it to 'Embedded resource'. Click Ok.
In Startup.cs add the following line to your app.UseSwaggerUI() call:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseSwaggerUI(c =>
{
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Your.Default.Namespace.Resources.Swagger_Custom_index.html");
});
//...
}
The identifier for the file resource in the above GetManifestResourceStream method is composed of:
your default namespace (i.e. 'Your.Default.Namespace')
the sub-path of your resource (i.e. 'Resources')
the filename of your resource (i.e. 'Swagger_Custom_index.html')
All three parts are concatenated using dots (NO slashes or backslashes here).
If you don't use a sub-path but have your resource in root, just omit part 2.
For people who separate ApplicationBuilder config methods on ASP.NET Core:
If the separated method/class is static, it is not possible to call GetType() because an object reference is required.
In that case, switch GetType() to MethodBase.GetCurrentMethod().DeclaringType
c.IndexStream = () => MethodBase.GetCurrentMethod().DeclaringType.Assembly.GetManifestResourceStream("xxx.index.html");

Showing DropDown for Client sdk in swaggerUI

I am having my api documetation in swagger. I would like to provide my users with Client sdk dropdown with options of php and java. below is my code.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(provider => Configuration);
services.AddTransient<IRegistrationRepository, ServiceUtilities>();
services.AddTransient<IClientServiceConnector, ClientServiceValidation>();
services.AddTransient<IEmailSender, EmailSender>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Title = "Onboarding API",
Version = "V1",
Description = "API to generate lead and return the url",
TermsOfService = "Please see terms and conditions",
Contact = new Swashbuckle.AspNetCore.Swagger.Contact {Name = "teggggrap",Email = "support#dd.com.au",Url= "https://www.dd.com.au/" }
});
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "gf.RegistrationApplication.xml");
c.IncludeXmlComments(xmlPath);
});
services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyHeader();
policy.AllowAnyMethod();
});
});
}
The consumers of your API can generate swagger-codegen to create clients for your API in their language of choice. You probably don't want to host this yourself, but you could give your users instructions to go to https://editor.swagger.io/ where they can upload your API spec and generate it from there.
I've generate my php and JS SDKs with Codegen. It's pretty easy to use and then you can push the folder to a public Github repo and from your Swagger UI, you can tell your consumers to visit and follow the Getting started section !
It generates README.md and docs for each model.
Here is my sdk

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