在asp.net mvc上检查上传的excel文件中的非法字符

我正在使用asp.net mvc 4制作一个网站,用户可以上传.xlsx文件并将数据保存到MSSQL表。 在保存数据之前,我想确保文件中没有非法字符,例如SQL注入语句。 到目前为止,我用$符号进行testing它工作正常,但它只会捕获如果一个单元格只有该字符,而不是在字符之间。 这是我的代码,

调节器

  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 Ax所说,避免SQL注入攻击的最好方法是参数化你的查询。 参数是值的占位符,而不是使用用户input的值。

例如:

 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