检查上传的 Excel 文件上的非法字符 asp.net mvc
本文关键字:net asp mvc 字符 文件 Excel 检查 非法 | 更新日期: 2023-09-27 18:33:24
我正在使用 asp.net MVC 4创建一个网站,用户可以在其中上传.xlsx
文件并将数据保存到MSSQL表。我想在保存数据之前确保文件中没有非法字符,例如SQL注入语句。到目前为止,我用$
符号进行了测试,它工作正常,但只有当单元格只有该字符而不是字符之间时,它才会捕获。这是我的代码,
控制器
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");
}
如何检查单元格中是否存在多个非法字符,这些字符可以作为单个字符或与其他字符一起出现?
正如@Sam Axe所说,避免SQL注入攻击的最佳方法是参数化查询。参数是值的占位符,而不是使用用户输入的值。
例如:
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();
}
}
以下是一些进一步的阅读:https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx