Back to listC#
ASP.NET Core - Web API Controller
Lv.5986@mukitaro6 playsDec 31, 2025
ASP.NET Core Web API controller with dependency injection, async operations, and structured logging.
preview.csharp
1[ApiController]2[Route("api/[controller]")]3public class ProductsController : ControllerBase4{5 private readonly IProductService _productService;6 private readonly ILogger<ProductsController> _logger;7 8 public ProductsController(IProductService productService, ILogger<ProductsController> logger)9 {10 _productService = productService;11 _logger = logger;12 }13 14 [HttpGet("{id}")]15 public async Task<ActionResult<Product>> GetProduct(int id)16 {17 var product = await _productService.GetByIdAsync(id);18 if (product == null)19 {20 _logger.LogWarning("Product {Id} not found", id);21 return NotFound();22 }23 return Ok(product);24 }25 26 [HttpPost]27 public async Task<ActionResult<Product>> CreateProduct([FromBody] CreateProductDto dto)28 {29 var product = await _productService.CreateAsync(dto);30 return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);31 }32}Custom problems are not included in rankings