Lesson 4 of 8
Action Results & Content Negotiation
ActionResult<T> provides compile-time type safety while allowing multiple HTTP response types. Content negotiation lets clients request JSON or XML responses using the Accept header - a REST principle.
Typed Results & Content Negotiation
// ━━ ActionResult<T> - type-safe with multiple response codes ━━
[HttpGet("{id:guid}")]
[ProducesResponseType<ProductDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProductDto>> GetById(Guid id, CancellationToken ct)
{
var product = await _service.GetByIdAsync(id, ct);
// Implicit conversion: return type is automatically wrapped in ActionResult<T>
if (product is null)
return NotFound(new ProblemDetails { Status = 404, Title = "Product not found", Detail = $"Product {id} does not exist" });
return product; // implicit: return Ok(product);
}
// ━━ Typed Results for Minimal APIs - no boxing, faster ━━
products.MapPost("/", async (CreateProductRequest req, IProductService svc) =>
{
var result = await svc.CreateAsync(req);
return TypedResults.Created($"/api/products/{result.Id}", result); // typed return
});
// ━━ Content negotiation - let clients choose format ━━
builder.Services
.AddControllers()
.AddXmlSerializerFormatters() // add XML support alongside JSON
.ConfigureApiBehaviorOptions(options =>
{
// Customize automatic 400 response
options.InvalidModelStateResponseFactory = context =>
{
var problem = new ValidationProblemDetails(context.ModelState)
{
Status = 400,
Title = "Validation Failed",
Type = "https://errors.myapp.com/validation"
};
foreach (var id in context.HttpContext.Items)
if (id.Key is "CorrelationId")
problem.Extensions["correlationId"] = id.Value;
return new BadRequestObjectResult(problem);
};
});
// Client uses Accept header:
// Accept: application/json → JSON response
// Accept: application/xml → XML response
// Accept: */* → server picks (JSON default)
// ━━ CreatedAtAction - 201 with Location header ━━
[HttpPost]
public async Task<IActionResult> Create(CreateProductRequest req, CancellationToken ct)
{
var product = await _service.CreateAsync(req, ct);
return CreatedAtAction(
nameof(GetById), // points to the GET action
new { id = product.Id }, // route values
product); // body
// Response: 201 Created + Location: /api/products/{id}
}
interface IProductService2 { Task<ProductDto> GetByIdAsync(Guid id, CancellationToken ct); Task<ProductDto> CreateAsync(dynamic r, CancellationToken ct); }
IProductService2 _service = null!;Tip
Tip
Practice Action Results Content Negotiation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Action Results Content Negotiation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Action Results Content Negotiation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?