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
Use ASP.NET Core Identity or external providers (OAuth2, OpenID Connect, Azure AD).
Apply [Authorize] attributes on controllers and actions.
Prefer policy-based authorization over hardcoded role checks.
[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
Use @Html.AntiForgeryToken() in MVC views.
Add [ValidateAntiForgeryToken] attribute on POST actions.
For APIs, rely on JWT tokens or custom headers.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateProfile(UserModel model)
{
// Safe processing
}
4. Secure Session & Cookies
Cookies are prime targets for attackers.
Best Practices
Use Secure, HttpOnly, and SameSite attributes.
Never store sensitive data (passwords, tokens) in cookies.
Encrypt sensitive data using ASP.NET Core Data Protection API.
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
Use global exception handling with UseExceptionHandler().
Log errors with Serilog, NLog, or Application Insights.
Avoid logging sensitive data.
app.UseExceptionHandler("/Home/Error");
6. Database Security
SQL injection remains one of the most exploited vulnerabilities.
Best Practices
Always use parameterized queries or Entity Framework LINQ.
Apply the principle of least privilege to DB accounts.
Encrypt sensitive fields (e.g., Always Encrypted in SQL Server).
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Email == email);
7. API Security
APIs are often the attack surface in modern applications.
Best Practices
Enforce HTTPS with the app.UseHttpsRedirection() .
Secure APIs with JWT tokens or OAuth2.
Implement rate limiting to mitigate DoS attacks.
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
Validate file extensions and MIME types.
Store files outside the webroot.
Restrict the file size in appsettings.json.
"Kestrel": {
"Limits": {
"MaxRequestBodySize": 10485760
}
}
9. Dependency & Configuration Security
Third-party libraries can introduce vulnerabilities.
Best Practices
Keep NuGet packages updated.
Run dotnet list package --vulnerable regularly.
Store secrets in Azure Key Vault or User Secrets.
Avoid keeping sensitive info in appsettings.json.
10. Performance & DoS Protection
Poor coding practices can make your app vulnerable to Denial-of-Service (DoS).
Best Practices
Utilize caching solutions (such as NCache or Redis) for improved performance.
Apply request throttling/rate limiting for APIs.
Prefer async/await for scalability.
Offload static files to a CDN.
Secure Coding Checklist
Enforce authentication & authorization.
Validate and sanitize all user input.
Enable CSRF protection.
Secure cookies and sessions.
Use centralized error handling and safe logging.
Prevent SQL Injection with EF Core.
Encrypt sensitive data in transit and at rest.
Secure APIs with HTTPS, JWT, and throttling.
Validate file uploads and scan for malware.
Keep dependencies updated and secrets secure.
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.