How to fix SQL Injection (Legacy & Modern)
in NancyFX
Executive Summary
NancyFX is a lightweight micro-framework for .NET that often gets paired with ADO.NET or Dapper. Because it doesn't force an ORM, devs frequently fall into the trap of concatenating 'parameters' or 'this.Request' data directly into raw SQL strings. If you're building queries by gluing strings together, you're handing over your DB to anyone with a browser and a copy of sqlmap.
The Vulnerable Pattern
public class UserModule : NancyModule
{
public UserModule()
{
Get["/users/{id}"] = parameters => {
string id = parameters.id;
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
// VULNERABLE: Direct string concatenation of untrusted input
var cmd = new SqlCommand("SELECT * FROM Users WHERE Id = '" + id + "'", conn);
var reader = cmd.ExecuteReader();
// ... process results
}
return 200;
};
}
}
The Secure Implementation
To kill SQLi in NancyFX, you must decouple the query logic from the data. First, leverage Nancy's dynamic routing to cast inputs to expected types (e.g., int). Second, never use '+' or string interpolation for SQL. If using Dapper (modern), pass an anonymous object to handle parameterization. If using raw ADO.NET (legacy), use the 'Parameters' collection. This ensures the DB driver treats the input as data, not executable code, neutralizing payload injection.
public class UserModule : NancyModule { public UserModule() { Get["/users/{id}"] = parameters => { // 1. Type validation: Ensure 'id' is actually an integer if (!int.TryParse(parameters.id, out int userId)) return 400;using (var conn = new SqlConnection(ConnectionString)) { // 2. Modern Approach: Use Dapper with anonymous object parameters var user = conn.QueryFirstOrDefault("SELECT * FROM Users WHERE Id = @Id", new { Id = userId }); // OR Legacy Approach: Use SqlParameter /* var cmd = new SqlCommand("SELECT * FROM Users WHERE Id = @Id", conn); cmd.Parameters.AddWithValue("@Id", userId); */ return Response.AsJson(user); } }; }
}
Your NancyFX API
might be exposed to SQL Injection (Legacy & Modern)
74% of NancyFX apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.