# How to Connect Two Systems Using .NET 6 Core Web API
In this article, we will learn how to connect two systems using .NET 6 Core Web API. We will create a simple Web API that provides weather data, and a client application that consumes the API and displays the data. We will use Visual Studio 2022, .NET 6 SDK, and SQL Server Express for this tutorial.
## Creating the Web API Project
First, we need to create a Web API project using the ASP.NET Core Web API template. To do this, open Visual Studio 2022 and select **Create a new project**. Then, select **ASP.NET Core Web API** and click **Next**. Give a name to your project, such as **WeatherForecast.Web.Api**, and click **Next**. In the next screen, select **.NET 6.0** as the framework and click **Create**.

You should see a default project structure like this:

In the **Program.cs** file, you can see that Swagger support is added automatically to our project. Swagger is a tool that helps us document and test our Web API. For more information on Swagger, see [ASP.NET Core web API documentation with Swagger / OpenAPI](^3^).
```csharp
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "WeatherForecast.Web.Api", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WeatherForecast.Web.Api v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
```
Now, let's run the project (Ctrl+F5) and see the default output. You should see a Swagger UI page like this:

You can click on the **WeatherForecast** endpoint and try it out. You should see some dummy weather data returned by the API.

## Adding a Model
Next, we need to add a model class that represents the weather data that we want to provide. To do this, create a folder called **Models** in the API project and add a class called **WeatherForecastModel**. Replace the generated code with the following code:
This class has four properties: **Date**, **TemperatureC**, **TemperatureF**, and **Summary**. The **TemperatureF** property is calculated from the **TemperatureC** property using a simple formula.
## Adding a Database Context
Now, we need to add a database context class that will manage the connection to the database and the operations on the data. To do this, we will use Entity Framework Core, which is an object-relational mapper (ORM) that simplifies data access in .NET applications.
First, we need to install the following NuGet packages to our API project:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
To install them, right-click on the project and select **Manage NuGet Packages**. Then, search for the packages and install them.

Next, create a folder called **Data** in the API project and add a class called **WeatherForecastDbContext**. Replace the generated code with the following code:
This class inherits from the **DbContext** class and has a **DbSet** property called **WeatherForecasts** that represents the collection of weather data in the database.
Next, we need to register the database context as a service in the **Program.cs** file. To do this, add the following line to the **builder.Services** section:
This line tells the application to use the **WeatherForecastDbContext** class and the SQL Server provider with the connection string named **WeatherForecastDb**.
Next, we need to add the connection string to the **appsettings.json** file. To do this, add the following section to the file:
This connection string specifies the server name, the database name, and the authentication mode for the SQL Server Express instance.
## Creating Database with Migrations
Now, we need to create the database and the tables using Entity Framework Core migrations. Migrations are a way of creating and updating the database schema based on the model classes.
To create the initial migration, open the Package Manager Console (Tools -> NuGet Package Manager -> Package Manager Console) and run the following command:
This command will create a folder called **Migrations** in the API project and a file called **[timestamp]_InitialCreate.cs** that contains the code to create the database schema.
![Migrations folder]
To apply the migration to the database, run the following command:
This command will execute the migration code and create the database and the tables in the SQL Server Express instance. You can verify this by opening the SQL Server Object Explorer (View -> SQL Server Object Explorer) and expanding the **(localdb)\\MSSQLLocalDB** node. You should see a database called **WeatherForecastDb** with a table called **WeatherForecasts**.
![SQL Server Object Explorer]
## Creating API Controller and Methods
Finally, we need to create an API controller class that will handle the requests to the Web API and provide the weather data. To do this, create a folder called **Controllers** in the API project and add a class called **WeatherForecastController**. Replace the generated code with the following code:
```csharp
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WeatherForecast.Web.Api.Data;
using WeatherForecast.Web.Api.Models;
namespace WeatherForecast.Web.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly WeatherForecastDbContext _context;
public WeatherForecastController(WeatherForecastDbContext context)
{
_context = context;
}
// GET: api/WeatherForecast
[HttpGet]
public async Task<ActionResult<IEnumerable<WeatherForecastModel>>> GetWeatherForecasts()
{
return await _context.WeatherForecasts.ToListAsync();
}
// GET: api/WeatherForecast/2022-02-26
[HttpGet("{date}")]
public async Task<ActionResult<WeatherForecastModel>> GetWeatherForecast(DateTime date)
{
var weatherForecast = await _context.WeatherForecasts.FindAsync(date);
if (weatherForecast == null)
{
return NotFound();
}
return weatherForecast;
}
// POST: api/WeatherForecast
[HttpPost]
public async Task<ActionResult<WeatherForecastModel>> PostWeatherForecast(WeatherForecastModel weatherForecast)
{
_context.WeatherForecasts.Add(weatherForecast);
await _context.SaveChangesAsync();
return CreatedAtAction("GetWeatherForecast", new { date = weatherForecast.Date }, weatherForecast);
}
// PUT: api/WeatherForecast/2022-02-26
[HttpPut("{date}")]
public async Task<IActionResult> PutWeatherForecast(DateTime date, WeatherForecastModel weatherForecast)
{
if (date != weatherForecast.Date)
{
return BadRequest();
}
_context.Entry(weatherForecast).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!WeatherForecastExists(date))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// DELETE: api/WeatherForecast/2022-02-26
[HttpDelete("{date}")]
public async Task<IActionResult> DeleteWeatherForecast(DateTime date)
{
var weatherForecast = await _context.WeatherForecasts.FindAsync(date);
if (weatherForecast == null)
{
return NotFound();
}
_context.WeatherForecasts.Remove(weatherForecast);
await _context.SaveChangesAsync();
return NoContent();
}
private bool WeatherForecastExists(DateTime date)
{
return _context.WeatherForecasts.Any(e => e.Date == date);
}
}
}
``
Source: Conversation with Bing, 2/26/2024
(1) Connecting a Web API With an ASP.NET Core MVC Application - Telerik. https://www.telerik.com/blogs/connecting-web-api-aspnet-core-mvc-application.
(2) Build a RESTful Web API with ASP.NET Core 6 - Medium. https://medium.com/net-core/build-a-restful-web-api-with-asp-net-core-6-30747197e229.
(3) How to access ASP.NET Core web server from another device. https://stackoverflow.com/questions/71044525/how-to-access-asp-net-core-web-server-from-another-device.
(4) asp.net web api - Connect multiple Databases to .NET core API project .... https://stackoverflow.com/questions/63992439/connect-multiple-databases-to-net-core-api-project-via-entity-framework-core.
(5) asp.net web api - How to communicate between to webApi .net core .... https://stackoverflow.com/questions/44530627/how-to-communicate-between-to-webapi-net-core.
(6) undefined. http://url-of-your-existing-api.
(7) github.com. https://github.com/Mythwrestler/projects.gloomhaven-tracker/tree/fa1cfe34b8938b0ed9c5d46e25009951e3e7da0c/ght-service%2FProgram.cs.
(8) github.com. https://github.com/Ramanareddy7/allprojects/tree/52dc4f7eff920c2d2ba4382ae70b0177faa30be5/Demo%2FProgram.cs.