I understand that parameterized queries is sufficient for preventing SQL injection. Is it good practice to validate the input parameters as well? What's a good way to validate the input parameters and where (controller, service, repository) do I validate them?
This is my controller method:
public async Task<ActionResult<List<Level>>> GetLevelsAsync([FromRoute] string Code, string Year)
{
int appId = IsoCode.FromName(Code).Id;
var result = await _sampleService.GetLevelsAsync(appId, Year);
return result;
}
This is my service method:
public async Task<List<Level>> GetLevelsAsync(int appId, string year)
{
if (string.IsNullOrWhiteSpace(year) == true)
throw new ArgumentNullException(nameof(year));
var result = await _sampleRepository.GetLevelsByYear(appId, year);
return result;
}
This is my repository method:
public async Task<List<Level>> GetLevelsByYear(int appId, string year)
{
if (string.IsNullOrWhiteSpace(year))
throw new ArgumentNullException(nameof(year));
var result = new List<Level>();
var parameters = new { AppId = appId, Year = year };
string sql = @"
SELECT *
FROM [Levels] as l, [LevelYears] as v
WHERE
v.LevelId = l.Id AND l.Active = 1 AND l.AppId = @AppId AND v.Year = @Year
ORDER BY v.Sort asc
";
using (IDbConnection db = new SqlConnection(_settings.SqlServerConnString))
{
try
{
result = db.Query<Level>(sql, parameters).ToList();
}
catch (Exception e)
{
_logger.LogError(e, "Error querying levels by year", new { appId, year });
throw;
}
}
return result;
}