I'm using asp.net MVC 4 to make a website where user can upload .xlsx
file and save the data to MSSQL table. I want to make sure that there is no illegal characters such as SQL injection statements in the file before saving the datas. So far I tested out with $
sign it works fine but it'll only catch if a cell has only that character, not in between characters. Here is my code,
Controller
public ActionResult BulkReadings()
{
string pathToExcelFile = System.IO.Path.Combine(Server.MapPath("~/ExcelFiles/"), "BulkReads.xlsx");
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var getSheet = from a in excelFile.Worksheet(sheetName) select a;
string Subject = "";
string Type = "";
string Reading = "";
foreach (var a in getSheet)
{
if (a["Subject"] == "$" || a["Type"] == "$" || a["Reading"] == "$") // This is where it checks for the "$" sign
{
if (System.IO.File.Exists(pathToExcelFile))
{
System.IO.File.Delete(pathToExcelFile);
}
TempData["meter_fail"] = "Error! Illegal Characters!";
return RedirectToAction("MeterManager");
}
else
{
Subject = a["Subject"];
Type = a["Type"];
Reading = a["Reading"];
try
{
Reading newEntry = new Reading();
newEntry.title = Subject;
newEntry.type = Type;
newEntry.reading1 = Reading;
rentdb.Readings.Add(newEntry);
}
catch
{
if (System.IO.File.Exists(pathToExcelFile))
{
System.IO.File.Delete(pathToExcelFile);
}
TempData["meter_fail"] = "Error! Upload Failed!";
return RedirectToAction("MeterManager");
}
}
}
rentdb.SaveChanges();
if (System.IO.File.Exists(pathToExcelFile))
{
System.IO.File.Delete(pathToExcelFile);
}
TempData["meter_success"] = "Reading(s) uploaded successfully!";
return RedirectToAction("MeterManager");
}
How can I check for multiple illegal characters that can be present as single or with other characters in the cell?
As @Sam Axe stated, the best way to avoid sql injection attacks is to parameterize your queries. Parameters are placeholders for values instead of using the user-input values.
For example:
using (SqlConnection conn = new SqlConnection(NorthwindConnectionString))
{
string query = "SELECT * FROM Products WHERE ProductID = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", Request.QueryString["Id"]);
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
DetailsView1.DataSource = rdr;
DetailsView1.DataBind();
}
}
Here is some further reading on it: https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.