Encountering an HTTP 400 Bad Request error while trying to upload a file through an AJAX post request to a

I'm encountering an issue whenever I try to upload a file that is not in .txt format. Text files work fine, but any other type of file results in an error. It seems like this problem didn't exist a year ago because the code went through extensive testing and it would have been caught early on that only .txt files could be uploaded. The server-side code is written in 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();
        }
    });

Server side:

<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

Answer №1

We successfully identified the problem, however, our solution may only be temporary. By using InvokeIsValidRequestString, we are able to prevent scripts from infiltrating api calls. Strangely, this .net function was wrongly marking any non-text file as harmful.

Here is the original code:

Return (New CustomRequestValidation).InvokeIsValidRequestString(HttpContext.Current, (New System.IO.StreamReader(HttpContext.Current.Request.InputStream)).ReadToEnd().Replace(",", ","), RequestValidationSource.Form, Nothing, -1)

And here is the new and improved code:

If HttpContext.Current.Request.Files.Count > 0 Then Return True Else Return (New CustomRequestValidation).InvokeIsValidRequestString(HttpContext.Current, (New System.IO.StreamReader(HttpContext.Current.Request.InputStream)).ReadToEnd().Replace(",", ","), RequestValidationSource.Form, Nothing, -1) End If

With our updated code, we now have a virus scanner in place that runs after these initial checks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring arrays and objects in handlebars: A closer look at iteration

Database Schema Setup var ItemSchema = mongoose.Schema({ username: { type: String, index: true }, path: { type: String }, originalname: { type: String } }); var Item = module.exports = mongoose.model('Item',ItemSchema, 'itemi ...

MAMP experiencing internal server error when calling PHP function using jQuery ajax

My apologies if this question seems repetitive or redundant, but I have been searching through numerous queries regarding calling a PHP function via ajax, yet I am unable to make it work. I am working with MAMP and below is a snippet of my code: index.htm ...

Ways to confirm if there have been any updates in Kendo Observable

Hey there! I have a form with specific fields that I've converted to Kendo Observable like this: var TITLE = $("#TITLE").val().trim(); var DESC = $("#DESC").val().trim(); Analysis.Kendo_VM = kendo.observable({ TITLE: TITLE != null ? TITLE : ...

Building a versatile assortment of items inside a larger group

I am working on creating a collection that contains a collection in two classes. Here is the code I have written so far: public class GenericReportInfo { public string ReportName { get; set; } public string ReportFileName { get; set; } public ...

Tips for utilizing the track OrbitControls in three.js

Presently, there are two blocks visible within the space: const material1 = new THREE.MeshBasicMaterial({color: '#00ff00'}); const cube1 = new THREE.Mesh(geometry, material1); cube1.position.set(0, 0, 0); const material2 = new THREE.MeshBasicMat ...

Error encountered in jQueryUI Autocomplete: the function 'this.source' is not defined

I have been working on incorporating a live search feature that scans through keys in a JSON obtained from a public API. To achieve this, I am utilizing Jquery UI. However, I encountered the following error and I am uncertain about how to resolve it. Un ...

An alert box displays N times when the submit button is clicked N times

Consider the following function: function validateForm() { var elements = ["firstname", "lastname", "password", "favfood", "favsport"]; document.getElementById('register').setAttribute('noValidate', true); document.getElement ...

Using data fetched from PHP in HTML via jQuery post: A step-by-step guide

I have created a function in jQuery that uses $.post to send data to a PHP file. The query in the PHP file is working fine and returning the data back successfully. JavaScript code: function send_agenda_data(cidade_data){ var data = {'cidade_dat ...

Tips for showcasing messages in a .dust file with connect-flash and express-messages in a Node application

I am currently working with Nodejs, Expressjs, and Kraken. I have been trying to display a message when a product is added on the index page, but despite several attempts to configure it, the messages are still not appearing as expected. Below is my config ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Issue: JavaScript code is not functional when operating on data obtained through an Ajax

I am experiencing an issue with my JavaScript code (abc.js) that is designed to run on a div element with the class of "one". While the script works perfectly fine on elements already present within the div in the HTML code, it fails to execute on data tha ...

run a function once ngFor has completed rendering the data

I'm attempting to run a function every time my ngFor finishes loading data from the API. However, the callback only works on the initial load of the ngFor. How can I make sure that the callback is executed whenever my ngFor data changes? I found a ...

Resetting component state in React Native is essential for maintaining the correct

I need to reset the state of specific states without affecting others. When a button is clicked, the values of present_count, total_count, present, and total should all be restored to their original state (0), while keeping the state of subjects and text u ...

Why does TrimStart only function when reassigning the text back to the variable?

textList = new List<string>(TextExtractor.newTextWithoutLinks); scrolledText = string.Join(Environment.NewLine, textList); combinedString = string.Join(Environment.NewLine, newText); scroller1.TextToScroll = scrolledText; textBox1.Text = combinedStri ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

Verify the presence of both class and id before modifying the content of the h1 tag and automatically redirecting the page

I'm encountering some issues triggering my JS/JQ on an HTML5 page. Essentially, I want to verify the existence of the following ID and class: ID: page_blog CLASS: page current <section class="page current" id="page_blog" style="z-index: 99; lef ...

What is the reason behind the browser crashing when a scrollbar pseudo-class is dynamically added to an iframe?

1. Insert a new iframe into your HTML: <iframe id="iframe-box" onload=onloadcss(this) src="..." style="width: 100%; border: medium none; "></iframe> 2. Incorporate the following JavaScript code into your HTML file ...

What could be the reason for the bottom edge of my central diagonal image having a darker border?

I can't figure out why the border on the bottom edge of my image is darker. You can check out the demo here. To get a closer look at the issue, you can open a software like GIMP and zoom in on the following image to see the difference in values: http ...

What is the most efficient way to clear the input field in Angularjs when the backspace or delete keys are pressed?

Is there a way to reset an input field with AngularJS when the backspace or delete keys are pressed? I've implemented this fantastic directive, and it's been working great, except for when the user uses the backspace or delete key to clear the f ...

What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL: https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc The parameter values can vary. This is the code snippet I use: getDataPlayer(payload) { let params if(payload.countryId && payl ...