c# - Check illegal characters on uploaded excel file in asp.net mvc -
i'm using asp.net mvc 4
make website user can upload .xlsx
file , save data mssql table. want make sure there no illegal characters such sql injection statements in file before saving datas. far tested out $
sign works fine it'll catch if cell has character, not in between characters. here 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 = in excelfile.worksheet(sheetname) select a; string subject = ""; string type = ""; string reading = ""; foreach (var in getsheet) { if (a["subject"] == "$" || a["type"] == "$" || a["reading"] == "$") // checks "$" 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 check multiple illegal characters can present single or other characters in cell? need badly! thanks.
as @sam axe stated, best way avoid sql injection attacks parameterize queries. parameters placeholders values instead of using user-input values.
for example:
using (sqlconnection conn = new sqlconnection(northwindconnectionstring)) { string query = "select * products 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 further reading on it: https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx
Comments
Post a Comment