Create ASP.NET Core Web API Project
On the Visual Studio, create new ASP.NET Core Web API Application project
Select Empty Template
Click Ok button to Finish
Add Configurations
Open Startup.cs file and add new configurations as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace LearnASPNETCoreWebAPIWithRealApps
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
Create Controller
Create new folder named Controllers. In this folder, create new controller named DemoController.cs, this file contains Web API as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreWebAPIWithRealApps.Controllers
{
[Route("api/demo")]
public class DemoController : Controller
{
[Produces("text/plain")]
[HttpGet("demo1/{id}")]
public async Task<IActionResult> Demo1(string id)
{
try
{
return Ok("Id: " + id);
}
catch
{
return BadRequest();
}
}
[Produces("text/plain")]
[HttpGet("demo2/{id1}/{id2}")]
public async Task<IActionResult> Demo2(string id1, int id2)
{
try
{
return Ok("Id1: " + id1 + ", Id2: " + id2);
}
catch
{
return BadRequest();
}
}
}
}
Structure of ASP.NET Core Web API Project
Testing Web API
Access restful web services use the following url: http://localhost:64967/api/demo/demo1/p01
Output
Id: p01
Access restful web services use the following url: http://localhost:64967/api/demo/demo2/p01/123
Output
Id1: p01, Id2: 123
Consume Web API from Console Application
Create Console App (.NET Framework) Project in Visual Studio.
Create DemoRestClientModel
DemoRestClientModel class contain methods call Web API
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 LearnASPNETCoreWebAPIWithRealApps_Client
{
public class DemoRestClientModel
{
private string BASE_URL = "http://localhost:64967/api/demo/";
public Task<HttpResponseMessage> Demo1(string id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
return client.GetAsync("demo1/" + id);
}
catch
{
return null;
}
}
public Task<HttpResponseMessage> Demo2(string id1, int id2)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
return client.GetAsync("demo2/" + id1 + "/" + id2);
}
catch
{
return null;
}
}
}
}
Run Console Application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace LearnASPNETCoreWebAPIWithRealApps_Client
{
class Program
{
static void Main(string[] args)
{
DemoRestClientModel demoRestClientModel = new DemoRestClientModel();
Console.WriteLine("Test Demo1 Web Method");
HttpResponseMessage httpResponseMessage = demoRestClientModel.Demo1("p01").Result;
HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode;
Console.WriteLine("Status Code: " + httpStatusCode);
bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);
string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
Console.WriteLine("\nTest Demo2 Web Method");
HttpResponseMessage httpResponseMessage2 = demoRestClientModel.Demo2("p02", 123).Result;
HttpStatusCode httpStatusCode2 = httpResponseMessage2.StatusCode;
Console.WriteLine("Status Code: " + httpStatusCode2);
bool isSuccessStatusCode2 = httpResponseMessage2.IsSuccessStatusCode;
Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode2);
string result2 = httpResponseMessage2.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result2);
Console.ReadLine();
}
}
}
Output
Test Demo1 Web Method
Status Code: OK
IsSuccessStatusCode: True
Result: Id: p01
Test Demo2 Web Method
Status Code: OK
IsSuccessStatusCode: True
Result: Id1: p02, Id2: 123
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Modern API Design with ASP.NET Core 2: Building Cross-Platform Back-End Systems
- Mastering ASP.NET Web API: Build powerful HTTP services and make the most of the ASP.NET Core Web API platform
- .NET Core in Action