ASP.NET Core Web API controllers are responsible for handling incoming HTTP requests and sending responses back to the client. This tutorial covers all you need to know about controllers, from basics to advanced concepts.
In ASP.NET Core, a Web API controller is a class that handles HTTP requests and responses. Controllers are derived from ControllerBase and can contain actions that perform operations on data and return responses.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Hello, World!");
}
}
Routing in ASP.NET Core is responsible for mapping incoming requests to action methods in controllers. This section explores how routing works and how to define routes using attributes.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult GetProduct(int id)
{
// Logic to retrieve a product by id
return Ok(new { Id = id, Name = "Sample Product" });
}
}
Controllers can return various types of action results that represent different HTTP responses. Understanding these results is crucial for effective API development.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ResponseController : ControllerBase
{
[HttpGet("[action]")]
public IActionResult GetNotFound()
{
return NotFound(); // Returns a 404 Not Found response
}
[HttpGet("[action]")]
public ActionResult<string> GetBadRequest()
{
return BadRequest("Invalid request"); // Returns a 400 Bad Request response
}
[HttpGet("[action]")]
public ActionResult<IEnumerable<string>> GetOk()
{
var data = new List<string> { "value1", "value2" };
return Ok(data); // Returns a 200 OK response with data
}
}
Handling requests involves receiving data, processing it, and returning responses. Learn about model binding, data validation, and handling complex scenarios in API development.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
[HttpPost]
public IActionResult Post([FromBody] UserInputModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Process the data (save/update)
return CreatedAtAction("Get", new { id = model.Id }, model);
}
}
public class UserInputModel
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
public string Email { get; set; }
}
Advanced techniques include handling file uploads, asynchronous operations, and using action filters to run code before or after controller actions.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
[HttpPost, DisableRequestSizeLimit]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded.");
var path = Path.Combine(Directory.GetCurrentDirectory(), "uploads", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok(new { message = "File successfully uploaded" });
}
}
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Net.Http;
[ApiController]
[Route("api/[controller]")]
public class AsyncController : ControllerBase
{
[HttpGet]
public async Task<IActionResult> GetExternalData()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("https://api.example.com/data");
var content = await response.Content.ReadAsStringAsync();
return Ok(content);
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
// Log action execution
base.OnActionExecuting(context);
}
public override void OnActionExecuted(ActionExecutedContext context)
{
// Log action execution complete
base.OnActionExecuted(context);
}
}
[ApiController]
[Route("api/[controller]")]
[LogActionFilter]
public class FilteredController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Action with filter applied");
}
}
Following best practices in controller design enhances the maintainability, readability, and functionality of your Web API.
Mastering ASP.NET Core Web API controllers is a crucial step towards building robust and scalable web applications. By understanding and implementing the concepts discussed in this tutorial, developers can effectively manage request handling, data processing, and response sending in their applications.