'HttpContext.Request.Form threw an exception of type 'System.InvalidOperationException' - why?

I have a strange problem. We are using C# for an ASP.NET MVC application, and JavaScript with jQuery and Data Tables for the frontend. In the frontend, a part of the code looks like this:

        table: "#restapiusers",
        ajax: {
            create: { url: "/restapiuser/RegisterUser" },
            edit: { url: "/restapiuser/EditUser" }
        },

The thing is that although both endpoints RegisterUser and EditUser get passed the payload in the same manner, only EditUser works.

        [HttpPost]
        public async Task<JsonResult> RegisterUser(RestApi_UserModel user_short)
        {
            var param = HttpContext.Request.Form.Keys.FirstOrDefault();

When I set a breakpoint to the above line and move the mouse cursor over "Form", it says that HttpContext.Request.Form threw an exception of type 'System.InvalidOperationException'.

The beginning of EditUser looks exactly the same and there the error does not occur. I am puzzled how this is possible.



Solution 1:[1]

In one of the code files there was the following text:

// Defaults for DT-Editor for all future instances
$.extend(true, $.fn.dataTable.Editor.defaults, {
    ajax: {
        create: {
            type: 'POST',
            //*** contentType: "application/json",
            //*** dataType: 'json',
            data: function (d) {
                d = JSON.stringify(Object.values(d.data))
                console.info("Payload", d);
                return d
            },
        },
        edit: {
            type: 'POST',
            //contentType: "application/json",
            //dataType: 'json',
            data: function (d) {
                d = JSON.stringify(Object.values(d.data))
                console.info("Payload", d);
                return d
            },
        }
    },
    idSrc: 'id',
});

I commented out the lines I marked with "***" and now it works. Apparently the contentType must not be "application/json" for the data to be passed via the first or default key of the form.

Solution 2:[2]

Change Request.Form to Request.Query

public async Task<JsonResult> RegisterUser(RestApi_UserModel user_short)
 {
   var param = HttpContext.Request.Query.Keys.FirstOrDefault();
}```

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adok
Solution 2 james simbi