I am using Swashbuckle and swagger to document my .NET Core (3.1) API project.
The documentation is updated fine at the swagger endpoint, when I use the publish functionality in Visual Studio 2019 16.4.2.
However using the release pipeline in Azure does achieve the same.
Using swagger gen like this:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "SqlViewService",
Version = "v1",
Description = "Alter views..."
});
});
I initially started adding the endpoint in the startup.cs class like this:
app.UseSwagger().UseSwaggerUI(s =>
{
s.SwaggerEndpoint("/swagger/v1/swagger.json", "SqlViewService v1");
});
And after searching a few articles and questions I have tried this:
app.UseSwagger().UseSwaggerUI(s =>
{
s.SwaggerEndpoint("/swagger/v1/swagger.json", "SqlViewService v1");
s.RoutePrefix = string.Empty;
});
And also this, adding current directory to the path:
app.UseSwagger().UseSwaggerUI(s =>
{
s.SwaggerEndpoint("./swagger/v1/swagger.json", "SqlViewService v1");
});
According to this article: https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio
None of the tries have worked. Does anybody have a good suggestion or actual solution?
I had to add the following with in the Startup.cs class in the Configure method:
s.RoutePrefix = "swagger";
In this section:
app.UseSwagger().UseSwaggerUI(s =>
{
s.SwaggerEndpoint("/swagger/v1/swagger.json", "SqlViewService v1");
s.RoutePrefix = "swagger";
});
To solve page not found which suddenly started appearing.
Which prevented me from seeing whether the changes I made in my release pipeline was working, once that was solved.
The path to the folder used for deployment was:
And as my folder path for files to deploy was wrong I was basically deploying into a folder within old application files, so the release was never "picked up" by IIS.
Related
I am working through the Microsoft Learn tutorials to "Create a web API with ASP.Net Core".
Under the heading, "Build and test the web API", at instruction (5) I am getting a response, "Unable to find an OpenAPI description".
For step (6) when executing the "ls" command I get the response, "No directory structure has been set, so there is nothing to list. Use the 'connect' command to set a directory structure based on an OpenAPI description". I have tried the "connect" command suggested here and have tried "dir" as an alternative to "ls".
I can successfully change directories in step (7) and execute the GET request for step (8) and receive the expected reply. However, it really bothers me the "ls" command is not working here and seems like an important function of the httprepl tool.
How can I get the "ls" command to work here or tell me why does it not work?
C:\Users\xxxx\source\repos\Learn\ContosoPizza>httprepl http://localhost:5000
(Disconnected)> connect http://localhost:5000
Using a base address of http://localhost:5000/
Unable to find an OpenAPI description
For detailed tool info, see https://aka.ms/http-repl-doc
http://localhost:5000/> ls
No directory structure has been set, so there is nothing to list. Use the "connect" command to set a directory structure based on an OpenAPI description.
http://localhost:5000/>
ADDED RESULTS OF SUGGESTIONS--
C:\Users\xxxx\source\repos\Learn\ContosoPizza>dotnet --version
3.1.412
C:\Users\xxxx\source\repos\Learn\ContosoPizza>dotnet add WebAPI.csproj package Swashbuckle.AspNetCore -v 5.6.3
Could not find project or directory `WebAPI.csproj`.
httprepl GitHub repo and MS Docs page
The solution for me was to simply trust localhost's SSL certification, which you can do with this command:
dotnet dev-certs https --trust
While doing the same Tutorial, a friend of mine noticed, that trusting the dev certificate, was already covered by the Tutorial, which I had overlooked doing the Tutorial myself. This is the official help site:
Trust the ASP.NET Core HTTPS development certificate on Windows and macOS.
Maybe this will still help someone with the same problem.
In step 5 HttpRepl emits the warning Unable to find an OpenAPI description, which means that it can't find the swagger endpoint, and therefore the ls command wont work.
I assume you are using VS Code and ASP.NET Core 5.0. Here is my output from running dotnet --version:
5.0.401
If we are using Visual Studio, then remember to enable swagger when you create the project - I am using Visual Studio 2019 to create the screenshot:
Specifying your OpenAPI description
To find out which endpoint to use, open the file Startup.cs and locate the code fragment that contains the text UseSwaggerUI. You should find this block of code:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
}
Use the endpoint you find and run the tool like this:
httprepl http://localhost:5000 --openapi /swagger/v1/swagger.json
If you do not find any references to swagger, then see None of the above worked, swagger isn't installed below, for how to install and configure swagger for your project.
Ignoring your environment
If specifying the Open API endpoint to use doesn't work, then you are not running your Web API in a development environment. So either use a development environment, or uncomment the if-statement while testing (to setup your environment for development, see Changing your environment below):
//if (env.IsDevelopment())
//{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
//}
Remember to restore the code you uncommented, if any, before you deploy to production.
Changing your environment
The profile your Web API is using, is specified in the file Properties\launchSettings.json. Open the file and search for ASPNETCORE_ENVIRONMENT. Then change the instances you find to:
"ASPNETCORE_ENVIRONMENT": "Development"
If this doesn't work, or the instances were already set to "Development", it means that you are not using any of the profiles specified in your launch settings. If no profile is used, ASPNETCORE_ENVIRONMENT defaults to "Production". When using the dotnet run command, the --launch-profile parameter lets you specify which profile to use:
dotnet run --launch-profile "name_of_profile"
As a last resort you can set the environment variable ASPNETCORE_ENVIRONMENT in the shell you are using, before you run the command dotnet run:
Bash
export ASPNETCORE_ENVIRONMENT=Development
CMD
set ASPNETCORE_ENVIRONMENT=Development
PowerShell
$env:ASPNETCORE_ENVIRONMENT='Development'
Then run the application without a profile :
dotnet run --no-launch-profile
The default ports, when running without a profile, should be 5000 or 5001. But read the output from the command, to see which ports it assigns to your Web API.
Please note, if you use VS Code to run your project, that VS Code may also have created launch settings in the .vscode\launch.json. It depends on how you have configured VS Code and what you allow it to do. I found some older articles, that claim that some extensions for VS Code, may interfere with the launch settings, but they didn't specify which ones.
None of the above worked, swagger isn't installed
I none of the above worked, it means you don't have swagger installed. Install swagger for your project and when done, try again.
Package Installation
Open your project in VS Code and run the following command from the Integrated Terminal and replace WebAPI.csproj with the name of your own project file:
dotnet add WebAPI.csproj package Swashbuckle.AspNetCore -v 5.6.3
You can of course run the command from outside VS Code, with your project folder as the current working directory.
Add and configure Swagger middleware
Add the Swagger generator to the services collection in the Startup.ConfigureServices method, as the last statement in the method:
public void ConfigureServices(IServiceCollection services)
{
[... other code here ...]
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
});
}
In the Startup.Configure method, enable the middleware for serving the generated JSON document and the Swagger UI, at the top of the method:
public void Configure(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
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");
});
[... other code here for setting up routing and the like ...]
}
To learn more about setting up swagger, profiles and the environment
Get started with Swashbuckle and ASP.NET Core
Managing Production and Development Settings in ASP.NET Core
Use multiple environments in ASP.NET Core
ASP.NET Core web API documentation with Swagger / OpenAPI
I had faced same issue. I have solved it by following:
In Developer PowerShell(VS 2022), Run 'dotnet run' command.
Keep this powershell as it is.
Now open new PowerShell and run "httprepl https://localhost:{PORT}"
You should be able to run api now.
You must be connected to the web server through dotnet run.
I created a new ASP.NET Core project with Visual Studio 2022 Preview and I am trying to run it as a Windows Service. I downloaded the latest Microsoft.Extensions.Hosting.WindowsServices package (6.0.0-preview.7.21377.19).
When researching online the function .UseWindowsService() goes into CreateHostBuilder method. But in the new template it looks different. I cannot understand where I should call .UseWindowsService in the new template. This is my current code, it looks like the service is starting but then when I browse to localhost:5000 it gives me 404 error
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Hosting.WindowsServices;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(); // <--- Added this line
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "MyWindowsService", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyWindowsService v1"));
}
app.UseAuthorization();
app.MapControllers();
app.Run();
I published my service exe like this
dotnet publish -c Release -r win-x64 --self-contained
Since simply using
builder.Host.UseWindowsService();
will not work with WebApplication.CreateBuilder() (see), but instead will throw the exception
Exception Info: System.NotSupportedException: The content root changed from "C:\Windows\system32\" to "...". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.
or rather will cause this error
Start-Service : Service 'Service1 (Service1)' cannot be started due to the following error: Cannot start service Service1 on computer '.'.
when trying to start the Service with Start-Service in PowerShell, I found a workaround that worked for me
using Microsoft.Extensions.Hosting.WindowsServices;
var options = new WebApplicationOptions
{
Args = args,
ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};
var builder = WebApplication.CreateBuilder(options);
builder.Host.UseWindowsService();
here:
An asp.net core web api application, using "UseWindowsService", reports an error “System.NotSupportedException: The content root changed. Changing the host configuration is not supported ” when starting the service
The following coding sets the lifetime to WindowsServiceLifetime and enables logging to the event log. In most cases this should be all you need to run the app as a Windows Service.
if (WindowsServiceHelpers.IsWindowsService())
{
appBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
appBuilder.Logging.AddEventLog(settings =>
{
if (string.IsNullOrEmpty(settings.SourceName))
{
settings.SourceName = appBuilder.Environment.ApplicationName;
}
});
}
I'm trying to use Swagger in my projects, but its not detecting my controllers.
This is the configuration of the swagger in my Startup.cs
...ConfigureServices method
services.AddSwaggerGen(opts =>
{
opts.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" });
});
...Configure method
app.UseSwagger();
app.UseSwaggerUI(opts =>
{
opts.SwaggerEndpoint("/swagger/v1/swagger.json", "API");
opts.RoutePrefix = string.Empty;
});
this is the structure of my code
If i have a folder with the name "Controllers" and i have a controller inside, the swagger find the controller and print it out in the swagger page, but if the controller is inside the feature folder, it does not find it.
here is the full code
Swashbuckle uses Microsoft.AspNetCore.Mvc.ApiExplorer, so if asp net core finds your controllers Swashbuckle will too. It doesn't care what folders you use.
If your controllers are in your startup project there shouldn't be anything you need to do. Just follow available tutorials. Refer to Get started with Swashbuckle and ASP.NET Core
I'm trying to add Swagger to my project. The error received is as follows.
No constructor for type 'Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator' can be instantiated using services from the service container and default values.
Since I haven't changed anything in Swagger binaries themselves, just installed the packages Swashbuckle.AspNetCore and Swashbuckle.AspNetCore.Swagger (both in version 4.0.1) I'm assuming that it's about the configuration. Following the suggestion here, I've set up the config shown below.
services.AddSwaggerGen(_ =>
{
_.SwaggerDoc("v1", new Info { Version = "v1", Title = "My API" });
});
app.UseSwagger();
app.UseSwaggerUI(_ => { _.SwaggerEndpoint("/swagger/v1/swagger.json", "API docs"); });
I'm not sure if I'm missing a package, if one of those I have is the wrong version or if the set config I'm providing isn't sufficient.
As the asker noted in a comment, what solved this for me was adding in a reference to Api Explorer in ConfigureServices.
Specifically the line required was:
services.AddMvcCore()
.AddApiExplorer();
You should register services.AddMvc(); in IServiceCollection, and configure app.UseMvc() in IApplicationBuilder in your application's Startup.cs
I am able to integrate the Swagge UI in my web api using Swashbuckle. I also want to explore the swagger codegen feature. Can somebody help in - how I can integrate swagger codegen into my web api project? Or do I need to download any tool? I want to be able it to host the codegen and pass the json/raml form specs to generate client in .net core.
I am not able to find enough docs on above.
EDIT : I want to know how I can host codegen in my WEBAPI.
Thanks!
Now, you can use Nswag. There are several code generator utilities - UI, Console, msbuild.
You should install "Swashbuckle.AspNetCore.Swagger" nuget package by right click your project and click manage nuget packages.
Then you should add these codes into your project startup place eg. Program.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
app.UseMvc();
}
It seems like you just want to generate C# from the OpenApi specification (your Swagger implementation provides the input) of your API.
To generate code (e.g. C#) from the OpenApi spec file of your API, you can do something like this:
java -jar .\openapi-generator-cli-5.0.0-beta3.jar generate -i https://localhost:xxxx/api/v1/swagger.json -g csharp
You have to download the OpenApi Generator Jar. Alternatively you can upload your code to a web generator. But I would always run this locally; you never know where your code ends up.