Updated : Jan 21, 2022 in Angular

how to create ASP.NET Core 3 Web API Project

On the Visual Studio, create new ASP.NET Core Web Application project

Input Project Name and select Project Location

Select Empty Template and click Create button to Finish

Structure of New Project

Add Configurations

Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCore3WebAPIWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Entities Class

Create Models folder. In this folder, create new class named Product.cs as below:

Product Entity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}

Create Controller

Create new folder named Controllers. In this folder, create new controller named ProductController.cs as below:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using LearnASPNETCore3WebAPIWithRealApps.Models;

namespace LearnASPNETCore3WebAPIWithRealApps.Controllers
{
    [Route("api/product")]
    public class ProductController : Controller
    {
        [Produces("application/json")]
        [HttpGet("find")]
        public async Task<IActionResult> Find()
        {
            try
            {
                var product = new Product() { Id = "p01", Name = "name 1", Price = 2 };
                return Ok(product);
            }
            catch
            {
                return BadRequest();
            }
        }

    }
}

Structure of ASP.NET Core 3 Web API Project

Testing Web API

Access Web API use the following url: http://localhost:18942/api/product/find

Output

{"id":"p01","name":"name 1","price":2.0}

Consume Web API from Console Application

Create Console App (.NET Framework) Project in Visual Studio.

Entity Class

Create Models folder in Console Application. In this folder, create new class named Product.cs as below:

Product Entity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}

Create ProductRestClientModel

ProductRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting library from Nuget Packages

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    public class ProductRestClientModel
    {
        private string BASE_URL = "http://localhost:18942/api/product/";

        public Task<HttpResponseMessage> Find()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return client.GetAsync("find");
            }
            catch
            {
                return null;
            }
        }
    }
}

Run Console Application

using LearnASPNETCore3WebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCore3WebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            ProductRestClientModel productRestClientModel = new ProductRestClientModel();

            HttpResponseMessage httpResponseMessage = productRestClientModel.Find().Result;

            HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode;
            Console.WriteLine("Status Code: " + httpStatusCode);

            bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
            Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);

            Product product = httpResponseMessage.Content.ReadAsAsync<Product>().Result;
            Console.WriteLine("Product Info");
            Console.WriteLine("Id: " + product.Id);
            Console.WriteLine("Name: " + product.Name);
            Console.WriteLine("Price: " + product.Price);

            Console.ReadLine();
        }
    }
}

Output

Status Code: OK
IsSuccessStatusCode: True
Product Info
Id: p01
Name: name 1
Price: 12.0

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x