In today’s digital landscape, application security is not optional; it’s a necessity. Developers often focus on features and performance but overlook secure coding practices, which can leave applications vulnerable to cyberattacks.

This article outlines practical secure coding guidelines for ASP.NET Core MVC & Web API developers, complete with real-world examples and best practices. By following these recommendations, you can build applications that are robust, secure, and resilient against common threats.

1. Authentication & Authorization

Authentication ensures only valid users can access your system, while authorization ensures they only access what they’re allowed.

Best Practices

  
    [Authorize(Roles = "Admin")]
public IActionResult Dashboard()
{
    return View();
}
  

2. Input Validation & Output Encoding

Unvalidated input is a common attack vector for SQL Injection and Cross-Site Scripting (XSS).

Best Practices

  
    public class UserModel
{
    [Required, StringLength(50)]
    public string Username { get; set; }

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

3. CSRF (Cross-Site Request Forgery) Protection

CSRF attacks trick users into executing unintended actions.

Best Practices

  
    [HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateProfile(UserModel model)
{
    // Safe processing
}
  

4. Secure Session & Cookies

Cookies are prime targets for attackers.

Best Practices

  
    services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.Strict;
});
  

5. Error Handling & Logging

Exposing stack traces in production can leak sensitive information.

Best Practices

  
    app.UseExceptionHandler("/Home/Error");
  

6. Database Security

SQL injection remains one of the most exploited vulnerabilities.

Best Practices

  
    var user = await _context.Users
    .FirstOrDefaultAsync(u => u.Email == email);
  

7. API Security

APIs are often the attack surface in modern applications.

Best Practices

  
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
    });
  

8. File Upload Security

File uploads can introduce malware and DoS vulnerabilities.

Best Practices

  
    "Kestrel": {
  "Limits": {
    "MaxRequestBodySize": 10485760
  }
}
  

9. Dependency & Configuration Security

Third-party libraries can introduce vulnerabilities.

Best Practices

10. Performance & DoS Protection

Poor coding practices can make your app vulnerable to Denial-of-Service (DoS).

Best Practices

Secure Coding Checklist

Conclusion

Security is a shared responsibility between developers, architects, and DevOps teams. By following these secure coding guidelines for ASP.NET Core MVC & Web API, you minimize the attack surface and safeguard your applications from common threats like XSS, CSRF, SQL injection, and DoS attacks.