问题
I am trying to do an asynchronous file upload using JavaScript in combination with a WebMethod in VB.NET
JavaScript:
xhr.open('POST', "upload.aspx/upload", true);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
var formData = new FormData();
// append the files
for (var i in files) {
formData.append(base.el.name, files[i]);
}
xhr.send(formData);
VB.NET:
<Web.Services.WebMethod(enableSession:=True)> _
Public Shared Function upload() As String
Return "Hello World!"
End Function
If I use content-type=application/x-www-form-urlencoded, or multipart/form-data the WebMethod does not get hit, if I use content-type=application/json, the WebMethod is hit, but the response is a 500 with message: Invalid JSON primitive: ------WebKitFormBoundary ...
Is there a way to make the AJAX WebMethod work with multipart form data?
回答1:
Seems .NET will not allow the multipart/form-data for the content-type:
JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks1
There is a built-in validation layer of protection that ASP.NET enforces for both GET and POST based ASP.NET AJAX web methods, which is that regardless of the HTTP verb being used, ASP.NET always requires that the HTTP Content-Type header is set to the value application/json. It this content type header is not sent, ASP.NET AJAX will reject the request on the server.
Seems the best way is to handle this using a generic .ashx file instead
来源:https://stackoverflow.com/questions/26262692/net-webmethod-with-xhrhttprequest-file-upload