This part will add a ASP.NET Core Web API into the app with Entity Framework code first approach.
- Step 1: Set up a new Database context
- Step 2: Work with a database using Entity Framework code first appoach.
- Step 3,:Scaffold API Controller with Action using Entity Framework
- Step 4: Add Swagger client for Web API
- Step 5: Run and Test app
At the end, you have an Web API built in a MVC app. The Web API is consumed by Swagger interface and can be consumed by any other interfaces, such as Postman.
Step 1: Set up a new Database Context
We make a new database context with the same model,
Model/Store.cs, and different database,
DB_Demo_API:
1. Create a new Database Context class, named DB_Demo_APIContext.cs,
- using Microsoft.EntityFrameworkCore;
-
- #nullable disable
-
- namespace MVCCallWebAPI.Models.DB
- {
- public partial class DB_Demo_APIContext : DbContext
- {
- public DB_Demo_APIContext()
- {
- }
-
- public DB_Demo_APIContext(DbContextOptions<DB_Demo_APIContext> options)
- : base(options)
- {
- }
-
- public virtual DbSet<Store> Stores { get; set; }
-
- }
- }
2. Add the new Connection in the appsettings.json file,
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
-
- "ConnectionStrings": {
- "DevConnection": "Data Source=localhost;Initial Catalog=pubs;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
- },
-
- "ConnectionStrings": {
- "DB_Demo_APIConnection": "Data Source=localhost;Initial Catalog=DB_Demo_API;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
- },
-
- "AllowedHosts": "*"
- }
3. Register the database connection context into Class
starup.cs inside ConfigureServices,
- public void ConfigureServices(IServiceCollection services)
- {
- // Register SQL database configuration context as services.
- services.AddDbContext<pubsContext>(options =>
- { options.UseSqlServer(Configuration.GetConnectionString("DevConnection"));
- });
- services.AddDbContext<DB_Demo_APIContext>(options =>
- {
- options.UseSqlServer(Configuration.GetConnectionString("DB_Demo_APIConnection"));
- });
-
- services.AddControllersWithViews();
- }
Step 2: Work with a database using Entity Framework code first appoach.
Click "Tools->NuGet Package Manager->Package Manager Console"(See A-Step 2), and run the PMC command (make them in one line),
- Add-Migration
- -Name initialMigration
- -Context DB_Demo_APIContext
We got two migration files under Migration folder,
Run PMC command
- Update-Database
- -Name initialMigration
- -Context DB_Demo_APIContext
We got the database table Stores created in database DB_Demo_API
Step 3: Scaffold API Controller with Action using Entity Framework
-
Right-click the Controllers folder.
-
Select Add > New Scaffolded Item.
-
Select API Controller with actions, using Entity Framework, and then select Add.
The generated code,
- Marks the class with the
[ApiController]
attribute. This attribute indicates that the controller responds to web API requests.
- Uses DI to inject the database context (
DB_Demo_APIContext
) into the controller. The database context is used in each of the CRUD methods in the controller.
Step 4: Add Swagger client for Web API
Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification.
If we created a new Web API project, the Swagger cient for Web API would be installed by default. In our current case, the Web API is created in a MVC module, so we need to install Swagger manually.
1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger
There are three main components to Swashbuckle (Swagger), we only need to install two of them: SwaggerGen and SwaggerUI, the Swagger would be included.
2. Register Swagger Client in startup.json file
Add the Swagger generator to the services collection in the
Startup.ConfigureServices
method,
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- // Register the Swagger generator, defining 1 or more Swagger documents
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v2", new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });
- });
- ......
- }
Enable the middleware for serving the generated JSON document and the Swagger UI, in the
Startup.Configure
method,
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- // 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/v2/swagger.json", "MVCCallWebAPI");
- });
- ......
- }
Now, we are almost ready to run the app.
Step 5: Run and Test the app
Before we run the app, modify the header of the file:
Views/Shared/_layout.cshtml Views again, shown below,
- <header>
- <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
- <div class="container">
- <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
- aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
- <ul class="navbar-nav flex-grow-1">
- <li class="nav-item">
- <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>
- </li>
- <li class="nav-item">
- <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
- </li>
- <li class="nav-item">
- <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
- </li>
- </ul>
- </div>
- </div>
- </nav>
- </header>
Now, we run the app,
Click Web API, we got the Swagger Client screen,
In this article (part I), we created an ASP.NET Core 5.0 MVC app and associated with a Web API service in it.
- MVC is a client/server app, with a web page as a client and SQL server as server, linked by Entity Framework;
- Web API is a Server side service, with a RESTful output for consumer that is linked to database by entity framework.
For our test purposes, MVC and Web API are against two different databases, MVC is against the database pubs, while Web API against database DB_Demo_API, which also gave us a chance to practice the entity framework database first approach and code first approach, respectively, in this mini project.
In the next
article, part II, we will demostrate the one line code approach for the
MVC Client to consume
Web API.