Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Using OpenAPI with .NET Core

<p>&nbsp;</p> <quillbot-extension-portal></quillbot-extension-portal>

September 16, 2020
Tom Deseyn
Related topics:
.NETLinuxMicroservices
Related products:
Developer Toolset

    In this article, we'll look at using OpenAPI with .NET Core. OpenAPI is a specification for describing RESTful APIs. First, I'll show you how to use OpenAPI to describe the APIs provided by an ASP.NET Core service. Then, we'll use the API description to generate a strongly-typed client to use the web service with C#.

    Writing OpenAPI descriptions

    Developers use the OpenAPI specification to describe RESTful APIs. We can then use OpenAPI descriptions to generate a strongly-typed client library that is capable of accessing the APIs.

    Note: Swagger is sometimes used synonymously with OpenAPI. It refers to a widely used toolset for working with the OpenAPI specification.

    Build the web service

    In this section, we'll use the open source Swashbuckle.AspNetCore package to provide an OpenAPI description of an ASP.NET Core application.

    We start by creating a webapi template application:

    $ dotnet new webapi -o WebApi1
    $ cd WebApi1
    

    The webapi template includes a REST API to get a weather forecast. The API is implemented in the WeatherForecastController.cs file.

    Next, we add the Swashbuckle.AspNetCore package:

    $ dotnet add package Swashbuckle.AspNetCore
    

    Now, we make a few edits to the Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
      {
        services.AddControllers();
    +
    +   services.AddSwaggerGen();
      }
    
    
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
        ....
    
        app.UseHttpsRedirection();
    
    +   app.UseSwagger();
    +
    +   app.UseSwaggerUI(c =>
    +   {
    +     c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    +   });
    +
        app.UseRouting();
    
        app.UseAuthorization();
    

    In the ConfigureServices method, we call AddSwaggerGen. Calling AddSwaggerGen makes the API description available. The API can then be consumed through ASP.NET Core's dependency injection (DI) system. UseSwagger uses these descriptions to create an HTTP endpoint at /swagger/v1/swagger.json. The UseSwaggerUI then provides a user interface (UI) at /swagger that allows users to easily consume the exposed API from a browser.

    Note: The methods called in Startup.cs accept a delegate for configuration. For useful options, see the ASP.NET Core documentation, Get started with Swashbuckle and ASP.NET Core.

    Run the app

    You can run the application and browse to the Swagger UI, which is shown in Figure 1.

    A screenshot of the weather app in the Swagger UI.
    Figure 1: The weather app in the Swagger UI.

    The Swashbuckle.AspNetCore packages picked up the ASP.NET endpoints. The exposed UI makes it easy to invoke the REST endpoints.

    Consuming OpenAPI descriptions

    In this section, we'll look at consuming a RESTful API that has an OpenAPI description. To consume the API, we'll use the open source package, NSwag.ApiDescription.Client.

    First, we create a new console project, and download the OpenAPI description from our ASP.NET application:

    $ dotnet new console -o console
    $ cd console
    $ mkdir openapi
    $ wget --no-check-certificate https://localhost:5001/swagger/v1/swagger.json -O openapi/weather.json
    

    Now, we'll make a few edits to the project file. These edits will be used to generate a strongly-typed client when the .NET project is built:

    <Project Sdk="Microsoft.NET.Sdk">
       <PropertyGroup>
         <OutputType>Exe</OutputType>
         <TargetFramework>netcoreapp3.1</TargetFramework>
       </PropertyGroup>
    +  <ItemGroup>
    +    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    +    <PackageReference Include="NSwag.ApiDescription.Client" Version="13.0.5" />
    +  </ItemGroup>
    +  <ItemGroup>
    +    <OpenApiReference Include="openapi/weather.json" Namespace="WeatherService">
    +      <ClassName>WeatherClient</ClassName>
    +      <OutputPath>WeatherClient.cs</OutputPath>
    +    </OpenApiReference>
    +  </ItemGroup>
     </Project>
    

    We've added references to the NSwag.ApiDescription.Client and Newtonsoft.Json packages. An OpenApiReference element refers to the API description that we downloaded earlier. It adds attributes that are required to generate the code, such as the class name, namespace, and filename.

    Build the client

    Now, we'll invoke the build command. Invoking the command generates a WeatherClient.cs file, which lives under the obj directory:

    $ dotnet build
    

    We can now edit the Program.cs file and use the strongly-typed WeatherClient class that we've just generated:

    static async Task Main(string[] args)
    {
      // Configure HttpClientHandler to ignore certificate validation errors.
      using var httpClientHandler = new HttpClientHandler();
      httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
    
      // Create WeatherClient.
      using var httpClient = new HttpClient(httpClientHandler);
      var weatherClient = new WeatherService.WeatherClient("http://localhost:5000", httpClient);
    
      // Call WeatherForecast API.
      var forecast = await weatherClient.WeatherForecastAsync();
      foreach (var item in forecast)
      {
        Console.WriteLine($"{item.Date} - {item.Summary}");
      }
    }
    

    Run the app

    Finally, we run the application:

    $ dotnet run
    7/1/2020 1:18:18 PM +02:00 - Mild
    7/2/2020 1:18:18 PM +02:00 - Bracing
    7/3/2020 1:18:18 PM +02:00 - Freezing
    7/4/2020 1:18:18 PM +02:00 - Balmy
    7/5/2020 1:18:18 PM +02:00 - Bracing
    

    As you can see, the weather report is mixed.

    Conclusion

    In this article, you learned about the OpenAPI specification, which is sometimes used synonymously with Swagger. Developers use the OpenAPI spec to describe RESTful APIs in preparation for being consumed by a client. I showed you how to use the Swashbuckle.AspNetCore package to provide an OpenAPI description of an API implemented using ASP.NET Core. Then, we used the NSwag.ApiDescription.Client package to generate a strongly-typed client capable of consuming the API.

    Last updated: February 5, 2024

    Recent Posts

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.