通过AJAX POST上传非TXT文件至.NET控制器时出现HTTP400错误
Let’s walk through the most likely causes and fixes for this issue, since you mentioned the code worked fine a year ago and only blocks non-.txt files now:
Key Areas to Investigate
1. Server-Side VB.NET Validation
Since your backend is VB.NET, the most probable culprit is a validation rule added in the last year that restricts uploads to .txt files. Check your server code for:
- Explicit checks on file extensions (e.g., using
Path.GetExtension(uploadedFile.FileName)to compare against.txt) - MIME type validation that only allows
text/plain - Hidden conditional logic that rejects non-text files before processing the request
2. AJAX/FormData Handling
Your provided AJAX snippet cuts off, so double-check these details in your client-side code:
- Ensure you’re not adding conditional logic that skips appending non-.txt files to the FormData object. Example of correct handling:
var uFile = new FormData(); var files = $(careerInformationSession.dg).find("#CareerSessionModel_Document_UploadFile").get(0).files; if (files.length > 0) { uFile.append("uploadFile", files[0]); // Avoid any checks here that exclude non-.txt files unless intentional } - Verify your AJAX request includes
contentType: falseandprocessData: false—these are mandatory for file uploads via FormData, and omitting them can cause 400 errors for non-text files with different encoding.
3. Web.config Restrictions
Check your web.config for settings that might block non-.txt files:
- Look for
requestFilteringrules undersystem.webServerthat explicitly allow only.txtextensions:<requestFiltering> <fileExtensions> <add fileExtension=".txt" allowed="true" /> <add fileExtension=".*" allowed="false" /> </fileExtensions> </requestFiltering> - Confirm
httpRuntimesettings likemaxRequestLengtharen’t triggering for larger non-text files (though 400 is more about validation than size, it’s worth ruling out).
4. Request Payload Comparison
Use your browser’s Network tab to inspect requests for .txt vs non-.txt files:
- Compare the Content-Disposition and Content-Type headers—non-text files should have appropriate MIME types (e.g.,
application/pdffor PDFs) - Check if any required form fields are missing when uploading non-text files, which could trigger a 400 error
Quick Validation Test
Temporarily disable any server-side file extension validation (if possible) and attempt to upload a non-.txt file. If it succeeds, you’ve confirmed the issue lies in recent validation rules—you can then adjust those rules to allow the necessary file types instead of blocking all except .txt.
内容的提问来源于stack exchange,提问作者Jason Schulman

