.NET WebMethod with xhrHttpRequest File Upload

时光总嘲笑我的痴心妄想 提交于 2020-03-06 07:23:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!