I've deployed a simple Web API in net5 with swagger enabled (using default settings), which means in Startup.cs:
Configure Services method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyCompany.WebApi", Version = "v1" });
});
Configure method:
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyCompany.WebApi v1"));
And i deploy the same application to 2 Local IIS websites, the first as an application of the Default WebSite running on default port 80, as shown below:
And the second as a Separate WebSite node running on port 8085, as shown below:
Then for the second (hosted as a separate WebSite node), all works fine, so i can see my API definition:
But for the first, hosted as an application under the Default Web Site the API documentation can not be loaded:
Even though the swagger.json file is accessible:
So it look's like swagger is searching for the index.html to display the Swagger-UI in the "root" of the WebSite, and in the case of the first option where the application is hosted under the Default WebSite folder it can not find a way to display the swagger UI. Do we need to add something specific in the swagger definition in this case ?
Thx for any responses !
Emmanuel.
Did you tried this:
app.UseSwaggerUI(c => c.SwaggerEndpoint("swagger/v1/swagger.json", "MyCompany.WebApi v1"));
i removed beginning '/' from swagger json path.
Related
I added Swashbuckle.AspNet.Core to my repository and initialized everything using the default values.
Although I can see JSON output from /swagger/v1/swagger.json opening /swagger/index.html just yields an empty page.
Why?
Here's my code
public void ConfigureServices(IServiceCollection services)
{
services
.AddSwaggerGen()
.AddControllers()
;
}
// This method gets called by the runtime once. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Options options)
{
if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
app
.UseHttpsRedirection()
.UseRouting()
.UseAuthorization()
.UseEndpoints(endpoints => endpoints.MapControllers())
.UseSwagger()
;
if (env.IsDevelopment()) app.UseSwaggerUI();
}
You haven't configured your Swashbuckle service correctly.
In your configureServices method, the call to AddSwaggerGen has "optional parameters", so the way you've specified it will work, but it's more common to do the following:
services.AddSwaggerGen(config =>
{
config.SwaggerDoc("v1", new OpenApiInfo() { Title = "Payment Card Info API", Version = "v1" });
});
Title is the title your Swagger Doc will show, and version is the advertised version of your API as displayed on your document, the FIRST "v1" parameter, is the version parameter that will be used in the actual swagger URL used to server the json file.
The code you place in your "Configure" method however, is NOT optional and must be done in a specific way.
app.UseSwagger();
app.UseSwaggerUI(config =>
{
config.SwaggerEndpoint("/swagger/v1/swagger.json", "Payment Card Info API");
});
The "UseSwaggerUI call MUST be configured manually, as it appears the defaults in the code simply don't work automatically.
By default your swagger json doc will always be at "/swagger/" + first version parameter in swaggerDoc call + "/swagger.json" (This can be changed, but I wouldn't recommend it)
Your swagger endpoint call, must be the actual URL the json is served at and a name of your choice to label it.
I would also strongly suggest wrapping your UseSwaggerUI call in an "env.IsDevelopment" call so that it's automatically turned off when you do a production build of your app, and thus will not make it available once your service is deployed.
Here's how I've done mine.
I have a Spring Boot application deployed and configured as AWS Route 53 > AWS Load Balance -> 2 EC2 instances which hosted the Spring Boot application.
The URL for the Swagger is
https://applicationXYZ.company.net/release/swagger-ui.html
I'm able to see the page without any issue. But we can't use the 'Tryout' feature because the Base URL is wrong.
On top of the page I do see information as
[ Base URL: service/release]
I have no idea where 'service' became my base URL. I also hit api-docs and also see 'server' in 'host' field.
Could you please help on this?
Note: I'm using Spring Boot Starter 2.0.8.RELEASE and Swagger 2.9.2 (without any Spring Security)
Thanks,
Did you ever try to make a redirect,
//Do redirection inside controller
#RequestMapping("/swagger")
public String greeting() {
return "redirect:/swagger-ui.html";
}
you can try to add bean too, inside main method,
#Bean
RouterFunction<ServerResponse> routerFunction() {
return route(GET("/swagger"), req ->
ServerResponse.temporaryRedirect(URI.create("swagger-ui.html")).build());
}
refer: How to change Swagger-ui URL prefix?
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"
});
});
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");
I created a basic Asp.net core 2.0 web application in the following way:
New Application => ASP.Net Core Web Application => Web Application =>
(MVC) => Change Authentication => Individual User Accounts (With docker enabled)
Debugging this will give you this:
This will obviously give you a 404, if you get rid of https://localhost:44360/ then the application is debugging there. I've seen this answer, but this didn't work for me.
I created a hosting.json as the answer suggested:
{
"server": "Microsoft.AspNetCore.Server.Kestrel",
"server.urls": "http://localhost:4000"
}
I added this to the Configure() method in startup:
var config = new ConfigurationBuilder()
.AddJsonFile("/app/hosting.json", optional: false)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
This didn't fix my startup issue. What am I doing wrong or what do i need to do to fix this debug issue?
I was seeing the same issue after creating a new project and installing Docker for Windows with Visual Studio Community 2017.
It appears that the docker-compose Property Pages had a bad Service URL property, which in my case was generated as: http://localhost:{ServicePort}/https://localhost:44339/
To fix the issue:
Right-click the docker-compose project
Select Properties
Replace Service URL with: http://localhost:{ServicePort}