Introduction
ASP.NET Core is a powerful framework for building RESTful APIs. It provides a robust set of features to create scalable and high-performance web services. This post will guide you through setting up an ASP.NET Core project, creating a RESTful API, and performing basic CRUD (Create, Read, Update, Delete) operations.
Setting Up ASP.NET Core
To get started with ASP.NET Core, you need to create a new web application project.
- Create a New ASP.NET Core Project:
- In Visual Studio, select “Create a new project”.
- Choose “ASP.NET Core Web Application” and click “Next”.
- Name the project “MyApiProject” and click “Create”.
- Select “API” and click “Create”.
Creating the Model and DbContext
In this example, we’ll create a simple API for managing products.
Example: Defining the Model and DbContext
using Microsoft.EntityFrameworkCore; namespace MyApiProject { public class Product { public int ProductId { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class AppDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyApiDb;Trusted_Connection=True;"); } } }
Explanation:
- Product Class: Represents the product data structure.
- AppDbContext: Manages the database connection and provides methods for interacting with the data.
- OnConfiguring: Configures the database connection string.
Creating the Controller
The controller handles HTTP requests and performs actions based on the requests.
Example: Creating the ProductsController
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyApiProject.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { private readonly AppDbContext _context; public ProductsController(AppDbContext context) { _context = context; } // GET: api/products [HttpGet] public ActionResult<IEnumerable<Product>> GetProducts() { return _context.Products.ToList(); } // GET: api/products/5 [HttpGet("{id}")] public ActionResult<Product> GetProduct(int id) { var product = _context.Products.Find(id); if (product == null) { return NotFound(); } return product; } // POST: api/products [HttpPost] public ActionResult<Product> PostProduct(Product product) { _context.Products.Add(product); _context.SaveChanges(); return CreatedAtAction(nameof(GetProduct), new { id = product.ProductId }, product); } // PUT: api/products/5 [HttpPut("{id}")] public IActionResult PutProduct(int id, Product product) { if (id != product.ProductId) { return BadRequest(); } _context.Entry(product).State = EntityState.Modified; _context.SaveChanges(); return NoContent(); } // DELETE: api/products/5 [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { var product = _context.Products.Find(id); if (product == null) { return NotFound(); } _context.Products.Remove(product); _context.SaveChanges(); return NoContent(); } } }
Explanation:
- ProductsController: Handles HTTP requests related to products.
- GET, POST, PUT, DELETE: Methods for handling CRUD operations.
Configuring the Startup Class
Configure the services and middleware in the Startup
class.
Example: Configuring Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; namespace MyApiProject { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
Explanation:
- ConfigureServices: Registers the
AppDbContext
and adds the controller services. - Configure: Sets up the middleware pipeline.
Testing the API
Run the application and test the API endpoints using a tool like Postman or your browser.
Example Requests:
- GET
/api/products
– Retrieves all products. - GET
/api/products/{id}
– Retrieves a product by ID. - POST
/api/products
– Adds a new product. - PUT
/api/products/{id}
– Updates an existing product. - DELETE
/api/products/{id}
– Deletes a product by ID.
Full Example Code
Here is the complete code for setting up an ASP.NET Core API with CRUD operations:
// Product.cs namespace MyApiProject { public class Product { public int ProductId { get; set; } public string Name { get; set; } public decimal Price { get; set; } } } // AppDbContext.cs using Microsoft.EntityFrameworkCore; namespace MyApiProject { public class AppDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyApiDb;Trusted_Connection=True;"); } } } // ProductsController.cs using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; namespace MyApiProject.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { private readonly AppDbContext _context; public ProductsController(AppDbContext context) { _context = context; } [HttpGet] public ActionResult<IEnumerable<Product>> GetProducts() { return _context.Products.ToList(); } [HttpGet("{id}")] public ActionResult<Product> GetProduct(int id) { var product = _context.Products.Find(id); if (product == null) { return NotFound(); } return product; } [HttpPost] public ActionResult<Product> PostProduct(Product product) { _context.Products.Add(product); _context.SaveChanges(); return CreatedAtAction(nameof(GetProduct), new { id = product.ProductId }, product); } [HttpPut("{id}")] public IActionResult PutProduct(int id, Product product) { if (id != product.ProductId) { return BadRequest(); } _context.Entry(product).State = EntityState.Modified; _context.SaveChanges(); return NoContent(); } [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { var product = _context.Products.Find(id); if (product == null) { return NotFound(); } _context.Products.Remove(product); _context.SaveChanges(); return NoContent(); } } } // Startup.cs using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; namespace MyApiProject { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } // appsettings.json { "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyApiDb;Trusted_Connection=True;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
Conclusion
Building RESTful APIs with ASP.NET Core is straightforward and powerful. By understanding how to set up a project, define models and DbContext,
create controllers, and perform CRUD operations, you can efficiently build and manage APIs for your applications.