How To Create an ASP.Net Core Web API Using Visual Studio 2019

In this article I will teach you how to create an ASP .Net Core Web API using Visual Studio 2019. If you don’t have Visual Studio 2019, you can download it from https://visualstudio.microsoft.com/ for free.

Advertisements

In installing Visual Studio 2019. Make sure to check ASP.NET and web development.

After installing Visual Studio 2019. Open Visual Studio 2019 and create a new ASP.Net Core Web Application project.

For the project name. Name it NetStore then select API in the project template.

Advertisements

The first thing we will do is to set up our Entity Framework. Create a new folder in your solution explorer and call it Model. Then inside the Model folder add new class and call it Product.

Add Properties Id, Name, Category and Price in the Product class. Your Product class should look like this.

namespace NetStore.Model
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public double Price { get; set; }
    }
}

Then add another class and call it NetStoreContext. This class will inherit the DbContext. Then add Product as a DbSet in your NetStoreContext and call it Products.

using Microsoft.EntityFrameworkCore;
namespace NetStore.Model
{
    public class NetStoreContext : DbContext
    {
        public NetStoreContext(DbContextOptions<NetStoreContext> options)
            :base(options)
        {

        }
        public DbSet<Product> Products { get; set; }
    }
}

In the solution explorer open appsettings.json file then add a ConnectionString configuration. Your appsettings.json now should look like the code below.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=NetStoreContext;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}

Change the ConnectionString value with your desired connection string.

Back in solution explorer. Open the Startup.cs and look for the method ConfigureServices. Here you can NetStoreContext in the services by adding this code in ConfigureServices method.

services.AddDbContext<NetStoreContext>(cfg => cfg.UseSqlServer(Configuration["ConnectionString"]));

Your Startup.cs now should look like this.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetStore.Model;

namespace NetStore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<NetStoreContext>(cfg => cfg.UseSqlServer(Configuration["ConnectionString"]));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
Advertisements

Build your project then open a command prompt. Using the command prompt navigate to the root directory of your project.

You can get the root directory of your project by doing a right click in the project name in solution explorer then select Open Folder in File Explorer. A folder will open then copy the location and paste it to the command prompt with the cd command.

cd your_root_folder_directory

then execute this command in the project root directory using command prompt to create our database.

dotnet ef database update

Then add an initial migration to the database by running this command.

dotnet ef migrations add InitialDb

Then update our database.

dotnet ef database update

After creating our let’s scaffold our web api. In the solution explorer right click to Controllers folder. Click add then controller.

Select API Controller with actions, using Entity Framework.

Select Product class for model. Then NetStoreContext for data context and let the controller name to default ProductsController.

Now run your application and use Postman to test your api. If you don’t have Postman installed in your machine. You can download it here
https://www.getpostman.com/downloads/

Advertisements

The image below is a sample of Post request. Change https://localhost:44373 based on your project url.

Then use the Get request to get the products in your database.

You can also try Put and Delete to update and delete products in your database.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s