Introduction
In the previous lessons, we implemented authentication, roles, and protection for the administration area. We can now assume that an administrator can sign in successfully. However, knowing who the user is does not make an application secure by itself. We must also verify that a state-changing request really originated from our application, render user-controlled data safely, and keep external values separate from database command text.
This lesson examines three common web security problems in an ASP.NET Core MVC application: CSRF, XSS, and SQL Injection. We will also connect these topics to model binding, server-side validation, output encoding, and safe input handling.
Our example uses the article creation workflow in the administration panel. The user submits an article title and summary, the application saves them to the database, and a Razor View later displays them.
The basic security rule is simple: never treat user-controlled data as trusted by default. Validate it, encode it for the correct output context, and pass it to database queries as data rather than as command text.
1. CSRF and antiforgery protection
Cross-Site Request Forgery occurs when a browser that is already authenticated to an application is tricked into sending an unwanted request from another site. Browsers can automatically include authentication cookies for the target domain, so an attacker may attempt to use the victim's existing permissions to perform a state-changing action.
For example, suppose the administration area deletes articles through a POST action. If an administrator is signed in and visits a malicious site, that site may attempt to cause the browser to send the delete request. Without an additional request-verification mechanism, the server may not be able to distinguish a legitimate action from a forged one. An antiforgery token provides that additional proof.
1.1. Validating a POST action
ASP.NET Core MVC provides antiforgery support when MVC services and the Form Tag Helper are used. We can protect an action with [ValidateAntiForgeryToken]:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize(Roles = "Admin")]
public class ArticlesController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var article = await _context.Articles.FindAsync(id);
if (article is null)
{
return NotFound();
}
_context.Articles.Remove(article);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}When a Form Tag Helper is used, the antiforgery field is normally generated automatically for a POST form. Because this lesson content does not use actual form elements, the form's source representation is shown below:
<form asp-action="Delete" asp-route-id="@article.Id" method="post">
<button type="submit">Delete</button>
</form>The Form Tag Helper adds a hidden request token. The validation filter compares the submitted token with the antiforgery cookie. If the token is missing or invalid, the action is not executed.
1.2. Applying protection broadly
Adding an attribute manually to every POST action is easy to forget. For MVC applications, a broad default policy is often safer. AutoValidateAntiforgeryTokenAttribute validates unsafe HTTP methods while excluding GET, HEAD, OPTIONS, and TRACE.
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});This approach reduces the chance that a newly added POST action is accidentally left unprotected. API endpoints and clients that do not use cookie authentication require a separate design; do not automatically apply the MVC form strategy to every API scenario.
1.3. Common CSRF mistakes
- Implementing a state-changing operation as a GET action.
- Removing antiforgery validation merely because a request returns HTTP 400.
- Adding a global filter and then broadly disabling it with
[IgnoreAntiforgeryToken]. - Sending an AJAX POST, PUT, or DELETE request without the expected token.
- Putting a request token in a URL query string or writing it to logs.
2. XSS and safe Razor output encoding
Cross-Site Scripting occurs when attacker-controlled data is rendered in a way that causes a browser to interpret it as executable code. The value may come from a form, query string, HTTP header, or data that was previously stored in the database.
Razor HTML-encodes ordinary variable output written with @. For example, the following value is rendered as text rather than interpreted as a script:
@{
var title = "<script>alert('test')</script>";
}
<p>@title</p>The rendered output is encoded into entities such as <script>alert('test')</script>. The browser therefore displays the characters instead of executing JavaScript.
2.1. Be careful with Html.Raw
Html.Raw disables Razor's normal encoding behavior. It should only be used when the content is trusted and deliberately needs to be interpreted as HTML.
<!-- Safe default: -->
<div class="summary">@Model.Summary</div>
<!-- Risky: treats user input as HTML -->
<div class="summary">@Html.Raw(Model.Summary)</div>If the CMS must support rich text, simply adding Html.Raw is not sufficient. Use a trusted sanitizer with an explicit allowlist of tags and attributes, and review URLs and event attributes. For a basic CMS, storing plain text is often the safer and more maintainable choice.
2.2. JavaScript and URL contexts
A value that is safe in ordinary HTML text is not automatically safe inside JavaScript code. Avoid concatenating user input into JavaScript. Prefer a data attribute or a separately serialized value, and read it as data on the client side. User input should also not be placed directly into a URL path. When it is used as a query-string value, it must be URL encoded.
<!-- Safe default for displaying and transporting text -->
<span data-article-title="@Model.Title">@Model.Title</span>On the client side, write the value as text with textContent rather than injecting it with innerHTML. The correct encoding strategy depends on the output context: HTML, an attribute, JavaScript, CSS, and a URL are not interchangeable contexts.
2.3. When should encoding happen?
The usual approach is to store the original value and encode it at the output boundary. The same title might later be used as HTML text, an email value, or a query-string parameter. Encoding too early can create double encoding and makes the stored data difficult to reuse correctly.
3. SQL Injection and parameterized queries
SQL Injection occurs when untrusted input is concatenated into SQL in a way that changes the command's structure. Normal EF Core LINQ expressions keep comparison values separate from the generated SQL:
public async Task<IActionResult> Search(string? term)
{
var query = _context.Articles.AsNoTracking();
if (!string.IsNullOrWhiteSpace(term))
{
term = term.Trim();
query = query.Where(a => a.Title.Contains(term));
}
var articles = await query
.OrderByDescending(a => a.CreatedAt)
.ToListAsync();
return View(articles);
}The value in term is not inserted into the SQL command text. EF Core sends it as a parameter, so the search phrase remains data rather than becoming part of the command structure.
3.1. When raw SQL is necessary
Special SQL, database-specific features, or a measured performance requirement may justify raw SQL. In that case, do not concatenate values into the command string:
var pattern = "%" + term + "%";
var articles = await _context.Articles
.FromSqlRaw(
"SELECT * FROM Articles WHERE Title LIKE {0}",
pattern)
.AsNoTracking()
.ToListAsync();Alternatively, use the interpolated query API, which treats interpolated values as parameters:
var pattern = "%" + term + "%";
var articles = await _context.Articles
.FromSqlInterpolated($"SELECT * FROM Articles WHERE Title LIKE {pattern}")
.AsNoTracking()
.ToListAsync();The following pattern is unsafe because the user value is directly inserted into SQL text:
var sql = $"SELECT * FROM Articles WHERE Title LIKE '%{term}%'";
var articles = await _context.Articles
.FromSqlRaw(sql)
.ToListAsync();Column names and sort directions usually cannot be supplied as ordinary SQL parameters. If those values must be selectable, use a fixed allowlist in application code. Never treat arbitrary user text as a column name, table name, or SQL fragment.
4. A secure user-input workflow
We can make article creation safer by applying the same principles consistently across the application layers.
4.1. Use an input model instead of binding the entity
Binding a database entity directly can allow the client to submit properties that should be controlled only by the server. Define a model containing only the fields that the form is allowed to provide:
using System.ComponentModel.DataAnnotations;
public sealed class ArticleCreateViewModel
{
[Required, StringLength(160)]
public string Title { get; set; } = string.Empty;
[Required, StringLength(500)]
public string Summary { get; set; } = string.Empty;
}Server-side validation is mandatory. Client-side validation improves the user experience, but it is not a security boundary because an attacker can disable or bypass browser scripts.
4.2. Validate and normalize in the controller
[HttpPost]
public async Task<IActionResult> Create(ArticleCreateViewModel input)
{
if (!ModelState.IsValid)
{
return View(input);
}
var article = new Article
{
Title = input.Title.Trim(),
Summary = input.Summary.Trim(),
CreatedAt = DateTime.UtcNow
};
_context.Articles.Add(article);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}The model is validated before the entity is created. Server-controlled properties such as Id, CreatedAt, AuthorId, and publication status should not come from the browser. The server must calculate or assign them.
4.3. Render the data safely
@model IEnumerable<Article>
@foreach (var article in Model)
{
<article>
<h3>@article.Title</h3>
<p>@article.Summary</p>
</article>
}Because the title and summary are rendered with ordinary Razor expressions, they are encoded by default. If the application is not intentionally supporting sanitized rich text, do not use Html.Raw.
5. Security checklist
- Use POST, PUT, PATCH, or DELETE for state-changing operations instead of GET.
- Enable antiforgery validation for cookie-based MVC forms.
- Bind forms to input models rather than binding database entities directly.
- Always check
ModelState.IsValidon the server. - Keep Razor's default output encoding enabled.
- Review every use of
Html.Raw,innerHTML, and string-built JavaScript. - Prefer EF Core LINQ; when raw SQL is required, use a parameterized API.
- Do not append user-controlled table names, column names, or SQL fragments directly to a query.
- Do not expose SQL statements, connection strings, tokens, or sensitive user data in error messages.
6. Short practice exercise
- Add POST handling and antiforgery protection to the article creation action in the administration area.
- Create an
ArticleCreateViewModeland limit the title and summary lengths. - Return the same View when the model is invalid; otherwise create the entity on the server.
- Render the title and summary in the listing View using ordinary
@Model.Propertyexpressions. - Enter
<script>alert('xss')</script>as a title and confirm that it is encoded rather than executed. - Implement article search first with LINQ and then with parameterized raw SQL. Do not use the concatenated SQL version.
- Remove the antiforgery token from a POST request and verify that the server rejects the request.
Conclusion
A secure MVC application requires more than authentication and role checks. CSRF protection verifies that a state-changing request includes a valid request token. Razor's automatic encoding reduces XSS risk, but that protection can be bypassed if methods such as Html.Raw are used carelessly. EF Core LINQ and parameterized raw SQL keep user input from changing the structure of a database command.
In later lessons, these principles will continue into error handling, logging, configuration, and deployment. The same discipline applies everywhere: validate input at the boundary, encode at the output context, parameterize database commands, and keep security decisions on the server.
Sources
- https://learn.microsoft.com/aspnet/core/security/anti-request-forgery
- https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes
- https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_ForgERY_Prevention_Cheat_Sheet.html
- https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html