ASP.NET Core  

File and Input Security in ASP.NET Core MVC and Web API Applications Introduction

When building modern applications with ASP.NET Core MVC or ASP.NET Web API , handling user input and file uploads securely is one of the most critical concerns. Poor input validation or insecure file handling can lead to serious vulnerabilities such as

  • SQL Injection

  • Cross-Site Scripting (XSS)

  • Path Traversal

  • Malware uploads and Remote Code Execution

  • Denial of Service (DoS)

In this article, we’ll walk through practical techniques and best practices to ensure file and input security in ASP.NET Core MVC and Web API–based applications.

Why File and Input Security Matters

User inputs (query strings, form fields, JSON payloads, and file uploads) are attack vectors . Without security checks, attackers may:

  • Upload malicious executables and scripts.

  • Manipulate file paths to access sensitive system files.

  • Exploit APIs with oversized payloads.

  • Inject malicious SQL queries.

  • Run stored XSS against other users.

Best Practices for Input Security

1. Validate Input Data

ASP.NET Core supports model validation using data annotations :

  
    public class RegisterModel
{
    [Required]
    [StringLength(50, MinimumLength = 3)]
    public string Username { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }
}
  

In your controller:

  
    if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}
  

Use FluentValidation for advanced validation scenarios.

2. Prevent SQL Injection

Never concatenate user input in SQL queries. Always use parameterized queries or Entity Framework LINQ .

  
    // Vulnerable
var users = db.Users.FromSqlRaw("SELECT * FROM Users WHERE Name = '" + name + "'");

// Safe
var users = db.Users.FromSqlInterpolated($"SELECT * FROM Users WHERE Name = {name}");
  

3. Prevent Cross-Site Scripting (XSS)

Razor views automatically HTML-encode variables:

  
    @Model.UserName  // Safe (encoded)
@Html.Raw(Model.Description) // Only use if sanitized first
  

Use the Ganss.XSS NuGet package to sanitize user-generated HTML.

4. Input Size Limiting (DoS Protection)

Limit maximum request size in Program.cs :

  
    builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10 MB
});
  

Best Practices for File Security

1. Restrict File Types

Only allow trusted extensions:

  
    var allowedExtensions = new[] { ".jpg", ".png", ".pdf" };
var ext = Path.GetExtension(file.FileName).ToLowerInvariant();

if (!allowedExtensions.Contains(ext))
{
    return BadRequest("Invalid file type.");
}
  

2. Validate File Size

  
    if (file.Length > 5 * 1024 * 1024) // 5 MB
{
    return BadRequest("File too large.");
}
  

3. Rename Files on Upload

Avoid storing user-supplied filenames directly:

  
    var safeFileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
var path = Path.Combine(_env.WebRootPath, "uploads", safeFileName);

using var stream = new FileStream(path, FileMode.Create);
await file.CopyToAsync(stream);
  

4. Store Files Outside Web Root

Always store files outside the wwwroot directory:

  
    var uploadsFolder = Path.Combine(_env.ContentRootPath, "App_Data", "Uploads");
  

Files should only be served via a controller action with proper authorization checks .

5. Scan Uploaded Files

Integrate antivirus scanning (e.g., ClamAV, Microsoft Defender API) before saving files permanently.

6. Secure File Access

Protect downloads with authentication and authorization:

  
    [Authorize]
public async Task<IActionResult> Download(Guid fileId)
{
    var file = await _fileService.GetFileAsync(fileId, User.Identity.Name);
    if (file == null) return NotFound();

    return File(file.Content, file.ContentType, file.FileName);
}
  

API-Specific Security

  • Always use HTTPS (TLS).

  • Sanitize JSON/XML inputs.

  • Implement rate limiting (use AspNetCoreRateLimit ).

  • Use JWT / OAuth2 authentication .

  • Avoid overposting —use DTOs instead of entity models.

  
    public class UserDto
{
    public string Username { get; set; }
    public string Email { get; set; }
}
  

OWASP Recommendations

  • Follow the OWASP Top 10 guidelines.

  • Apply anti-forgery tokens in MVC ( @Html.AntiForgeryToken() ).

  • Set Content Security Policy (CSP) headers.

  • Regularly patch and update dependencies.

Conclusion

Securing files and inputs in ASP.NET Core MVC and Web API is not optional; it’s essential for protecting your users and your business. By enforcing strict validation, safe file handling, secure storage, and strong API defenses , you minimize risks from XSS, SQL injection, path traversal, malware uploads, and DoS attacks.