Create Database
Create a database named LearnASPNETCoreWebAPIWithRealApps. This database have a table: Product table as below:
USE LearnASPNETMVCWithRealApps
/* Table structure for table `product` */
GO
CREATE TABLE Product (
Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name varchar(250) NULL,
Price money NULL,
Quantity int NULL,
Status bit NOT NULL
)
/* Dumping data for table `product` */
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 1', 20.0000, 4, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 2', 12.0000, 8, 0)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 3', 4.0000, 3, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 4', 17.0000, 8, 1)
Structure of Product Table
Data of Product Table
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 Libraries
Use NuGet add Libraries need for Entity Framework Core as below:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.Proxies
Create AppSettings File
Select Project and right click to select Add\New Item Menu
Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish
In appsettings.json file and new configurations as below:
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=LearnASPNETCoreWebAPIWithRealApps;user id=sa;password=123456"
}
}
Entity Class
Create new folder named Models. In Models folder, create new entity class as below:
Product Entity
Create new class named Product.cs as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LearnASPNETCore3WebAPIWithRealApps.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public bool Status { get; set; }
}
}
Create Data Context
In Models folder, create new class named DataContext.cs as below:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace LearnASPNETCore3WebAPIWithRealApps.Models
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options)
: base(options)
{
}
public DbSet<Product> Product { get; set; }
}
}
Add Configurations
Open Startup.cs file and add new configurations as below:
using LearnASPNETCore3WebAPIWithRealApps.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LearnASPNETCore3WebAPIWithRealApps
{
public class Startup
{
public IConfiguration configuration { get; }
public Startup(IConfiguration _configuration)
{
configuration = _configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var connectionString = configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<DataContext>(options => options.UseLazyLoadingProxies().UseSqlServer(connectionString));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
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.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using LearnASPNETCoreWebAPIWithRealApps.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace LearnASPNETCore3WebAPIWithRealApps.Controllers
{
[Route("api/product")]
public class ProductController : Controller
{
private DataContext db;
public ProductController(DataContext _db) {
db = _db;
}
[Consumes("application/json")]
[Produces("application/json")]
[HttpPut("update")]
public async Task<IActionResult> Update([FromBody] Product product)
{
try
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return Ok(product);
}
catch
{
return BadRequest();
}
}
}
}
Structure of ASP.NET Core 3 Web API Project
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 int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public bool Status { get; set; }
}
}
Create ProductRestClientModel
ProductRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting library from Nuget Packages
using LearnASPNETCore3WebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
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> Update(Product product)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client.PutAsJsonAsync("update", product);
}
catch
{
return null;
}
}
}
}
Run Console Application
using LearnASPNETCore3WebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
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)
{
var productRestClientModel = new ProductRestClientModel();
var product = new Product()
{
Id = 4,
Name = "Name 99",
Price = 111,
Quantity = 222,
Status = false
};
var httpResponseMessage = productRestClientModel.Update(product).Result;
var productInfo = httpResponseMessage.Content.ReadAsAsync<Product>().Result;
var httpStatusCode = httpResponseMessage.StatusCode;
Console.WriteLine("Status Code: " + httpStatusCode);
bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);
Console.WriteLine("Update Product");
Console.WriteLine("Id: " + productInfo.Id);
Console.WriteLine("Name: " + productInfo.Name);
Console.WriteLine("Price: " + productInfo.Price);
Console.WriteLine("Quantity: " + productInfo.Quantity);
Console.WriteLine("Status: " + productInfo.Status);
Console.ReadLine();
}
}
}
Output
Status Code: OK
IsSuccessStatusCode: True
Update Product
Id: 4
Name: Name 99
Price: 111.0
Quantity: 222
Status: False