How to use Swagger Codegen with .net core - c#

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.

Related

When to use Microsoft Extensions Logging and Application Insights Asp NETCore in Azure Functions

I am so confused while enabling logging in azure functions in .NET Core 6 using application insights. I had explored lot of sites but still in dilemma what exactly the difference between the nuget packages and when to use at which situations.
microsoft.extensions.logging.applicationinsights
microsoft.applicationinsights.aspnetcore
I had understand that if we want custom telemetry, we should use microsoft.applicationinsights.aspnetcore
I had created separate azure functions with separate nuget packages and I am able to see logs.
With microsoft.extensions.logging.applicationinsights package and used ILogger in function classes.
I added below piece of code in azure function startup
builder.Services.AddSingleton(new TelemetryConfiguration { ConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING")});
with Microsoft.ApplicationInsights.AspNetCore package , I injected Di and used ITelemetryClient in function classes
I added below piece of code in azure function startup
var options = new ApplicationInsightsServiceOptions { ConnectionString = SharedMethods.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING") };
builder.Services.AddApplicationInsightsTelemetry(options);

Why is HttpRepl unable to find an OpenAPI description? The command "ls" does not show available endpoints

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.

SwashBuckle upgrade does not enable OAS3.0

We are making an upgrade of our webapi to enable OAS3.0 in our dotnet Core application and from the documentation it seems that it is only supported in SwashBuckle.Aspnetcore 5.4.1 + versions. As mentioned here : https://github.com/domaindrivendev/Swashbuckle.AspNetCore
So we upgraded our SwashBuckle.Aspenetcore to 5.4.1. When we ran the applicaiton though, it still does produce swagger 2.0 instead of OAS 3.01. Now, the documentation on the same page does not specify anything special that we have todo when you upgrade from swagger2.0-->OAS3.0
Currently my little configuration looks like below:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/myapp/swagger/v1/swagger.json", "API name");
c.RoutePrefix = "myapp/swagger";
c.DisplayRequestDuration();
c.DisplayOperationId();
});
The documentation on the page also point to a page mentioning the support for OAS3.0 in a link here: https://swagger.io/specification/
But again not code to reference to. Can someone point me to specifics of how to upgrade my API from swagger 2.0 to OAS 3.0?
It looks like you have c.SerializeAsV2 = true somewhere in the code. To output OpenAPI 3.0, this option must be false.

Swagger not detecting controllers inside feature folder

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

Do I need a Global.asax.cs file at all if I'm using an OWIN Startup.cs class and move all configuration there?

Let's say for example in a brand new ASP.NET MVC 5 application made from the MVC with Individual Accounts template, if I delete the Global.asax.cs class and move it's configuration code to Startup.cs Configuration() method as follow, what are the downsides?
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ConfigureAuth(app);
}
}
The upsides for me is that when upgrading ASP.NET 4 applications to ASP.NET 5 and using pieces that now must be configured in the Startup.cs class, I'm not doing dependency injection and other configuration in two different classes that seem related to starting up, and configuration.
Startup.Configuration gets called slightly later than Application_Start, but I don't think the difference will matter much in most cases.
I believe the major reasons we kept the other code in Global.asax are:
Consistency with previous versions of MVC. (That's where everybody currently expects to find this code.)
Ability to add other event handlers. In Global.asax, you can handle other methods like Session_Start and Application_Error.
Correctness in a variety of authentication scenarios. The Startup.Configuration method is only called if you have Microsoft.Owin.Host.SystemWeb.dll in your bin directory. If you remove this DLL, it will silently stop calling Startup.Configuration, which could be hard to understand.
I think the third reason is the most important one we didn't take this approach by default, since some scenarios don't include having this DLL, and it's nice to be able to change authentication approaches without invalidating the location where unrelated code (like route registration) is placed.
But if none of those reasons apply in your scenario, I think you'd be fine using this approach.
For those looking for the complete steps: If you are looking to create a OWIN based, IIS hosted web API, these steps should get you there:
File -> New -> Project
In the dialogue, Installed -> templates -> Other Project types -> Visual Studio Solutions -> Blank Solution targeting .NET 4.6
On the solution, right click, add Project -> Web -> ASP.NET Web Application (targeting .NET 4.6)
3.1 Now In the ASP.NET 4.5 templates, choose Empty as the template
3.2 This creates a blank solution with two nuget packages:
Microsoft.CodeDom.Providers.DotNetCompilerPlatform v 1.0.0
Microsoft.Net.Compilers v 1.0.0
Install the following packages:
Install-Package Microsoft.AspNet.WebApi.WebHost -Version 5.2.3
Install-Package Microsoft.AspNet.WebApi -Version 5.2.3
Install-Package WebApiContrib.Formatting.Razor 2.3.0.0
For OWIN:
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Then add Startup.cs with Configuration method:
[assembly:OwinStartup(typeof(namespace.Startup))]
public class Startup
{
/// <summary> Configurations the specified application. </summary>
/// <param name="app">The application.</param>
public static void Configuration(IAppBuilder app)
{
var httpConfiguration = CreateHttpConfiguration();
app
.UseWebApi(httpConfiguration);
}
/// <summary> Creates the HTTP configuration. </summary>
/// <returns> An <see cref="HttpConfiguration"/> to bootstrap the hosted API </returns>
public static HttpConfiguration CreateHttpConfiguration()
{
var httpConfiguration = new HttpConfiguration();
httpConfiguration.MapHttpAttributeRoutes();
return httpConfiguration;
}
}
Now add a class that inherits from ApiController, annotate it with RoutePrefix attribute and the action method with Route + HttpGet/PutPost (representing the Http verb you're after) and you should be good to go
This is my understanding of how starting/hosting a web application evolved as it's all pretty confusing to follow. A small summary:
1. Classic ASP.NET: Write only the application code to run in the last step of the mandatory IIS pipeline
2. ASP.NET with OWIN: Configure a .NET webserver and write your application code. No longer directly coupled to IIS, so you're no longer forced to use it.
3. ASP.NET Core: Configure both the host and the webserver to use and write your application code. No longer mandatatory to use a .NET webserver if you target .NET Core instead of the full .NET Framework.
Now I'll go a bit more into detail of how it works and which classes are used to start the application:
Classic ASP.NET
Classic ASP.NET applications have the Global.asax file as entry point. These applications can only be run in IIS and your code gets executed at the end of the IIS pipeline (so IIS is responsible for CORS, authentication... before your code even runs). Since IIS 7 you can run your application in integrated mode which integrates the ASP.NET runtime into IIS. This enables your code to configure functionality which wasn't possible before (or only in IIS itself) such as url rewriting in the Application_Start event of your Global.asax file or use the new <system.webserver> section in your web.config file.
ASP.NET with OWIN
First of all OWIN is not a library but a specification of how .NET web servers (for example IIS) interact with web applications. Microsoft themselves have an implementation of OWIN called project Katana (distributed through several different NuGet packages). This implementation provides the IAppBuilder interface you encounter in a Startup class and some OWIN middleware components (OMC's) provided by Microsoft. Using IAppBuilder you basically compose middleware in a plug-and-play way to create the pipeline for the webserver (in addition to only the ASP.NET pipeline in IIS7+ as in the point above) instead of being tied to the IIS pipeline (but now you use a middleware component for CORS, a middleware component for authentication...). Because of this, your application is not specifically coupled to IIS anymore and you can run it on any .NET Webserver, for example:
The OwinHost package can be used to self-host your application with a Katana webserver.
The Microsoft.Owin.Host.SystemWeb package is used to host your OWIN application in IIS7+ in integrated mode, by subscribing your middleware to the correct lifetime events internally.
The thing that makes everything so confusing is that Global.asax is still supported together with the OWIN Startup class, while they can both do similar things. For example you could implement CORS in Global.asax and authentication using OWIN middleware which becomes really confusing.
My rule of thumb is to remove the Global.asax file alltogether in favor of using Startup whenever I need to add OWIN.
ASP.NET Core
ASP.NET Core is the next evolution and now you can target either .NET Core or the full .NET Framework. When you target .NET Core you can run your application on any host which supports the .NET Standard. This means you are no longer restricted to a .NET webserver (as in the previous point), but can host your application in Docker containers, a linux webserver, IIS...
The entry point for an ASP.NET Core web application is the Program.cs file. There you configure your host and again specify your Startup class where you configure your pipeline. Using OWIN (by using the IAppBuilder.UseOwin extension method) is optional, but fully supported.

Categories