using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using MyApp.Models; namespace MyApp.Controllers { [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly MyDbContext _context; public ProductsController(MyDbContext context) { _context = context; } [HttpGet] public ActionResult> GetAll() { return _context.Products.ToList(); } [HttpGet("{id}")] public ActionResult
GetById(int id) { var product = _context.Products.FirstOrDefault(p => p.Id == id); if (product == null) { return NotFound(); } return product; } } }
using Microsoft.AspNetCore.Mvc; using MyApp.Models; namespace MyApp.Controllers { [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly MyDbContext _context; public ProductsController(MyDbContext context) { _context = context; } [HttpPost] public IActionResult Create(Product product) { _context.Products.Add(product); _context.SaveChanges(); return CreatedAtAction(nameof(GetById), new { id = product.Id }, product); } } }This example creates an ApiController for the Products table in a database, with a POST method to create a new product. The method takes a Product object as a parameter, adds it to the database, and returns a 201 Created response with the newly created product and its location.