尝试通过AJAX文件上传文件到.NET控制器时HTTP400错误请求

时间:2018-04-25 14:37:24

标签: .net ajax api file upload

尝试上传任何非.txt文件的文件时,我收到此错误。文本文件正常工作。我假设这个问题在一年前没有发生,因为这段代码经历了多个测试阶段,并且很容易发现除.txt之外的所有文件都无法上传。服务器代码是VB.net:

AJAX:

            var uFile = new FormData();
            var files = $(careerInformationSession.dg).find("#CareerSessionModel_Document_UploadFile").get(0).files;
            if (files.length > 0) {
                uFile.append("UploadedImage", files[0]);
                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: careerInformationSession.api + "UploadFile",
                    contentType: false,
                    processData: false,
                    data: uFile,
                    success: function (data) {
                        careerInformationSession.uploadSuccess(data);
                    },
                    error: function (ts) {
                        careerInformationSession.callFailure();
                    }
                });

服务器:

    <System.Web.Http.HttpPost> 
    Public Function UploadFile() As String
        Dim returnValue As String = String.Empty
        If HttpContext.Current.Request.Files.AllKeys.Any() Then
            ' Get the uploaded image from the Files collection
            Dim httpPostedFile As System.Web.HttpPostedFile = HttpContext.Current.Request.Files("UploadedImage")
            If httpPostedFile IsNot Nothing Then
                Dim validateFile As New ValidateAjaxPostedFile(5120, "JPG,PNG,PDF,JPEG,GIF", httpPostedFile)
                If validateFile.Validate() Then
                    SessionManager.SetSessionData(CWDS.Framework.Utilities.SessionManager.SubSystem.EM, CAREER_INFO_SESSION_FILE, validateFile.FileData)
                    SessionManager.SetSessionData(CWDS.Framework.Utilities.SessionManager.SubSystem.EM, CAREER_INFO_SESSION_FILE_NAME, System.IO.Path.GetFileName(httpPostedFile.FileName))
                Else
                    Return returnValue
                End If
            End If
        End If
        Return returnValue
    End Function

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我们发现了问题,但可能只是暂时修复。我们调用InvokeIsValidRequestString来防止在api调用中插入脚本。此.net函数将任何非文本文件标记为恶意,原因不明。

原始代码:

返回(New CustomRequestValidation).InvokeIsValidRequestString(HttpContext.Current,(New System.IO.StreamReader(HttpContext.Current.Request.InputStream))。ReadToEnd()。Replace(&#34;,&#34;,& #34;,&#34;),RequestValidationSource.Form,Nothing,-1)

新代码:

如果HttpContext.Current.Request.Files.Count&gt; 0然后                 返回True             其他                 返回(New CustomRequestValidation).InvokeIsValidRequestString(HttpContext.Current,(New System.IO.StreamReader(HttpContext.Current.Request.InputStream))。ReadToEnd()。Replace(&#34;,&#34;,&#34; ,&#34;),RequestValidationSource.Form,Nothing,-1)             结束如果

我们的新代码可行,因为我们仍然拥有在这些初始步骤之后运行的病毒扫描程序。