c# - Post a file using HTTPWebrequest (multipart/form-data) gives an error (A potentially dangerous Request.Form value was detected from the client) -
i want send file using http post mvc web application. file contains html tags. below code have tried.
public void postmultiplefiles(string url, string[] files) { string boundary = "----------------------------" + datetime.now.ticks.tostring("x"); httpwebrequest httpwebrequest = (httpwebrequest)webrequest.create(url); httpwebrequest.contenttype = "multipart/form-data; boundary=" + boundary; httpwebrequest.method = "post"; httpwebrequest.keepalive = true; httpwebrequest.credentials = system.net.credentialcache.defaultcredentials; stream memstream = new system.io.memorystream(); byte[] boundarybytes =system.text.encoding.ascii.getbytes("\r\n--" + boundary +"\r\n"); string formdatatemplate = "\r\n--" + boundary + "\r\ncontent-disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; string headertemplate = "content-disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n content-type: application/octet-stream\r\n\r\n"; memstream.write(boundarybytes, 0, boundarybytes.length); (int = 0; < files.length; i++) { string header = string.format(headertemplate, "file" + i, files[i]); //string header = string.format(headertemplate, "uplthefile", files[i]); byte[] headerbytes = system.text.encoding.utf8.getbytes(header); memstream.write(headerbytes, 0, headerbytes.length); filestream filestream = new filestream(files[i], filemode.open, fileaccess.read); byte[] buffer = new byte[1024]; int bytesread = 0; while ((bytesread = filestream.read(buffer, 0, buffer.length)) != 0) { memstream.write(buffer, 0, bytesread); } memstream.write(boundarybytes, 0, boundarybytes.length); filestream.close(); } httpwebrequest.contentlength = memstream.length; stream requeststream = httpwebrequest.getrequeststream(); memstream.position = 0; byte[] tempbuffer = new byte[memstream.length]; memstream.read(tempbuffer, 0, tempbuffer.length); memstream.close(); requeststream.write(tempbuffer, 0, tempbuffer.length); requeststream.close(); try { webresponse webresponse = httpwebrequest.getresponse(); stream stream = webresponse.getresponsestream(); streamreader reader = new streamreader(stream); string var = reader.readtoend(); } catch (exception ex) { response.innerhtml = ex.message; } httpwebrequest = null; }
but when request received mvc application, exception occured. exception - "a potentially dangerous request.form value detected client". reason exception , how can post file?
you can decorate action allowhtml attribute:
[allowhtml] public void postmultiplefiles(string url, string[] files)
note potential security risk! see this msdn article more info.
Comments
Post a Comment