Web API with MVC.pdf - ASP.NET core Create a web API with...

This preview shows page 1 - 12 out of 28 pages.

ASP.NET core Create a web API with ASP.NET Core MVC By: Mahboob Ali
Project setup Let start with creating new project. File New Project Select ASP.NET Core Web Application template, named BookStoreAPIWithMVC Select API from the template and click OK.
Test Your API If you run your API at this point. The project template creates a WeatherForcast API. Call the Get method from the browser to test the API. Now the port number will again randomly chosen, but you can always right-click and go to the properties of you project and by selecting Debug on the left side. Change the APP URL:
JSON response [ { "date": "2019-07-16T19:04:05.7257911-06:00", "temperatureC": 52, "temperatureF": 125, "summary": "Mild" }, { "date": "2019-07-17T19:04:05.7258461-06:00", "temperatureC": 36, "temperatureF": 96, "summary": "Warm" }, { "date": "2019-07-18T19:04:05.7258467-06:00", "temperatureC": 39, "temperatureF": 102, "summary": "Cool" }, { "date": "2019-07-19T19:04:05.7258471-06:00", "temperatureC": 10, "temperatureF": 49, "summary": "Bracing" }, { "date": "2019-07-20T19:04:05.7258474-06:00", "temperatureC": -1, "temperatureF": 31, "summary": "Chilly" } ] Default response from the API. You can delete all the created default API files that get created with the project or keep them We will change the project and the targeted JSON response any way
Adding a Model Class In Solution Explorer , right-click the project. Select Add > New Folder . Name the folder Models . Right-click the Models folder and select Add > Class . Name the class Book and select Add .
Book.cs namespace BookStoreAPIWithMVC.Models { public class Book { public int BookID { get; set; } public string BookName { get; set; } public bool Available { get; set; } } }
Install NUGet packages Install Microsoft.EntityFrameworkCore.SqlServer Install Microsoft.EntityFrameworkCore.InMemory Install Microsoft.EntityFrameworkCore.Relational Install Microsoft.EntityFrameworkCore.Tools
Adding a Database Context The database context is the main class that coordinates Entity Framework functionality for a data model. Right-click the Models folder and select Add > Class . Name the class BookContext and click Add .
BookContext.cs using Microsoft.EntityFrameworkCore; namespace BookStoreAPIWithMVC.Models { public class BookContext : DbContext { public BookContext(DbContextOptions<BookContext> options) : base(options) { } public DbSet<Book> BookLists { get; set; } } }
Open your Startup.cs file and lets register the DBContext for the services.

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture