---
title: "Write Secure API in .NET Core"  
description: "When you create APIs using ASP.NET Core, you must ensure that your API is protected from unauthorized access, data leaks, and attacks like SQL Injection, XSS."  
author: "Ravi Vishwakarma"  
published: 2026-03-16  
updated: 2026-03-16  
canonical: https://answers.mindstick.com/blog/97/write-secure-api-in-dot-net-core  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 3 minutes  

---

# Write Secure API in .NET Core

Building a secure API is one of the most important tasks in modern [web development](https://www.mindstick.com/services/technologies). When you create APIs using [ASP.NET Core](https://www.mindstick.com/articles/326150/asp-dot-net-core-why-it-is-best-suited-for-banking-and-finance-sectors), you must ensure that your API is protected from [unauthorized access](https://www.mindstick.com/forum/158562/how-can-wireless-networks-be-secured-against-unauthorized-access-and-attacks), data leaks, and attacks like [SQL Injection](https://www.mindstick.com/blog/227/sql-injection), XSS, and brute force login attempts.

In this blog, we will learn **how to write secure API in .NET Core** with practical steps [and best practices](https://www.mindstick.com/articles/341641/scaling-databases-concepts-strategies-and-best-practices).

## 1. Use HTTPS Always

- The first rule of API security is to use **HTTPS** instead of HTTP.
- HTTPS encrypts data between client and server.

### Enable HTTPS in ASP.NET Core

```cs
app.UseHttpsRedirection();
```

In `launchSettings.json`

```plaintext
"applicationUrl": "https://localhost:5001"
```

Benefit

- Data encryption
- Prevent man-in-the-middle attack
- Secure login & tokens

## 2. Use Authentication (JWT Token)

- [Authentication](https://www.mindstick.com/blog/177/authentication-and-authorization-in-asp-dot-net) is required to verify the user.
- Best way in .NET Core API → **JWT Authentication**

Use package:

```plaintext
Microsoft.AspNetCore.Authentication.JwtBearer
```

### Configure JWT

```cs
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true
    };
});
```

### Use Authorize

```cs
[Authorize]
[HttpGet]
public IActionResult GetData()
{
    return Ok("Secure Data");
}
```

Benefit

- Only logged users can access API
- Secure token based login
- Used in production systems

## 3. Use Authorization (Role Based)

- Authentication = Who are you
- Authorization = What you can do

```cs
[Authorize(Roles = "Admin")]
public IActionResult DeleteUser()
{
}
```

You can also use policy:

```cs
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly",
        policy => policy.RequireRole("Admin"));
});
```

## 4. Validate Input Data

- Never trust user input.
- Use [Model Validation](https://www.mindstick.com/blog/646/model-validation-in-asp-dot-net-mvc-4).

```cs
public class UserModel
{
    [Required]
    public string Name { get; set; }

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

In Controller:

```cs
if (!ModelState.IsValid)
    return BadRequest(ModelState);
```

Prevents

- SQL Injection
- Invalid data
- Crash errors

## 5. Use Exception Handling Middleware

- Never show real error to user.
- Create global exception handler.

```cs
app.UseExceptionHandler("/error");
```

[Custom middleware](https://www.mindstick.com/interview/34485/how-to-write-custom-middleware-in-asp-dot-net-core):

```cs
app.Use(async (context, next) =>
{
    try
    {
        await next();
    }
    catch (Exception ex)
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("Error");
    }
});
```

Benefit

- Hide server details
- Prevent hacking info leak

## 6. Use Logging

- Use logging to track errors and attacks.
- Built-in logging in ASP.NET Core

```cs
ILogger<HomeController> _logger;
_logger.LogError("Error occurred");
```

You can use:

- Serilog
- NLog
- File logging
- Database logging

Benefit

- Debug issues
- Track hackers
- Monitor API

## 7. Use Rate Limiting

Prevent too many requests.

Install:

```plaintext
AspNetCoreRateLimit
```

Example:

```cs
services.AddInMemoryRateLimiting();
```

Limit requests per minute.

Prevents

- DDOS
- Brute force
- API abuse

## 8. Use CORS Properly

Allow only trusted domains.

```cs
builder.Services.AddCors(options =>
{
    options.AddPolicy("MyPolicy",
        policy =>
        {
            policy.WithOrigins("https://mindstick.com")
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
});
```

Use:

```cs
app.UseCors("MyPolicy");
```

Prevents unauthorized calls

## 9. Use Stored Procedure / Parameterized Query

Never write raw SQL.

Bad

```plaintext
"select * from user where id=" + id
```

Good

```plaintext
command.Parameters.AddWithValue("@id", id);
```

Prevents SQL Injection.

## 10. Use API Versioning

Secure and maintain API versions.

Install:

```plaintext
Microsoft.AspNetCore.Mvc.Versioning
```

```cs
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/user")]
```

Benefit

- Safe updates
- No breaking changes
- Production ready

## Conclusion

To write **secure API in .NET Core**, always follow:

- Use HTTPS
- Use JWT Authentication
- Use Authorization
- Validate Input
- [Handle Exceptions](https://www.mindstick.com/forum/158866/how-do-you-handle-exceptions-in-python-provide-an-example)
- Use Logging
- Rate Limiting
- CORS
- Parameterized Query
- [API Versioning](https://www.mindstick.com/articles/333603/a-guide-to-implementing-api-versioning-and-version-management-in-dot-net-core)

---

Original Source: https://answers.mindstick.com/blog/97/write-secure-api-in-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
