What HTTP status code and response should be returned when an upload fails validation (wrong type, too large, missing file)?
Short answer
Return a 400 Bad Request with a clear, structured error message (ideally following the ProblemDetails format) explaining specifically what validation failed -- wrong content type, size exceeded, or no file provided -- so the client can present an actionable, specific message to…
Advertisement
AModel answer
Return a 400 Bad Request with a clear, structured error message (ideally following the ProblemDetails format) explaining specifically what validation failed -- wrong content type, size exceeded, or no file provided -- so the client can present an actionable, specific message to the end user rather than a generic failure.
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile? file) {
if (file is null || file.Length == 0)
return BadRequest(new ProblemDetails { Title = "No file provided", Status = 400 });
if (file.Length > MaxSize)
return BadRequest(new ProblemDetails { Title = "File exceeds maximum size of 10MB", Status = 400 });
if (!AllowedTypes.Contains(file.ContentType))
return BadRequest(new ProblemDetails { Title = $"Content type {file.ContentType} not allowed", Status = 400 });
await _storageService.SaveAsync(file.FileName, file.OpenReadStream());
return Ok();
}Real-world example
An image upload endpoint returns a structured ProblemDetails response specifying exactly which validation rule failed (file too large vs wrong type vs missing entirely), letting the client UI show a precise, helpful error message instead of a generic 'upload failed' banner.
Likely follow-ups
- How does this integrate with the global IExceptionHandler for consistent error formatting?
- Should validation errors be logged, and at what severity?
Related topics