Introduction

Application security has become one of the most critical aspects of modern software development. Whether you are building ASP.NET Core MVC, Web API, or .NET Framework applications, or even desktop apps, securing your application should always be a top priority.

Attackers continuously look for vulnerabilities such as SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), insecure authentication, and sensitive data exposure.

In this article, we will explore the best practices for application security in C# development with practical recommendations and ready-to-use code snippets.

1. Authentication and Authorization

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

2. Preventing SQL Injection

Always use Entity Framework LINQ or parameterized queries. Never concatenate user input directly into SQL strings.

Safe (Entity Framework LINQ) :

C#
  
    var user = db.Users.FirstOrDefault(u => u.Username == username);

Safe (ADO.NET with parameters) :

C#
  
    var cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @username", conn);
cmd.Parameters.AddWithValue("@username", username);

Vulnerable (SQL Injection) :

C#
  
    var query = $"SELECT * FROM Users WHERE Username = '{username}'";

3. Input Validation and Output Encoding

C#
  
    @Html.DisplayFor(model => model.Comment)  // Razor safely encodes output

4. Secure Configuration

C#
  
    app.UseHttpsRedirection();

5. Protect Against Cross-Site Attacks

CSRF Protection

C#
  
    @Html.AntiForgeryToken()

And in the controller:

C#
  
    [HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitForm(MyModel model)
{
    // Handle form safely
}

CORS Protection

Restrict origins and headers:

C#
  
    app.UseCors(builder =>
    builder.WithOrigins("https://trusteddomain.com")
           .AllowAnyHeader()
           .AllowAnyMethod());

6. Logging and Monitoring

C#
  
    _logger.LogInformation("User {UserId} logged in at {Time}", userId, DateTime.UtcNow);

7. Secure APIs

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

8. Dependency and Patch Management

9. Secure File Handling

C#
  
    var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
var path = Path.Combine("uploads", fileName);

10. Cryptography and Data Protection

C#
  
    using (var rng = RandomNumberGenerator.Create())
{
    byte[] tokenData = new byte[32];
    rng.GetBytes(tokenData);
    string token = Convert.ToBase64String(tokenData);
}

11. Secure Development Lifecycle

12. Compliance and Standards

Real-World Security Checklist for C# Developers

Here’s a quick reference you can use in your projects:

Authentication & Authorization

Data Protection

Web Security

File Handling

Logging & Monitoring

Dependencies & Config

Testing & SDLC

Conclusion

Security should never be an afterthought in software development. By following these best practices in your C# applications , you can significantly reduce the risk of common vulnerabilities and safeguard your users’ data.

Remember the golden rules:

By adopting these practices, developers can build secure, reliable, and resilient C# applications that stand strong against today’s cyber threats.