Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Incorrect Content-Type: " exception throws angular mvc 6 application

I'm developing an application using asp.net, mvc6 and angularjs on my angular service. When I make a request to an action method, I get no passed data. When I have checked the request, I could see an exception that caused by:

  • Form '((Microsoft.AspNet.Http.Internal.DefaultHttpRequest)this.Request).Form' threw an exception of type 'System.InvalidOperationException' Microsoft.AspNet.Http.IFormCollection {System.InvalidOperationException}

exception message saying "Incorrect Content-Type:application/json;charset=UTF-8"

my angular service

return $http({ method: 'POST', url: 'home/createEvent', eventDetails: event })
                .success(function(data, status, headers, config) {
                    return data;
                })
                .catch(function(data, status, headers, config) {
                    console.log(data);
                });

on my controller

[HttpPost]
public IActionResult CreateEvent([FromBody]Event eventDetails)
{
    return Json(new {dsd=""},
        new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});

}
like image 429
Gayan Avatar asked Nov 14 '15 18:11

Gayan


4 Answers

The accepted answer didn't work for me. For me, the solution was to add a header to the $http call:

        $http({
                url: "/install",
                method: "POST",
                data: data,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                }
            })
            .success(...);
like image 154
Dave Thieben Avatar answered Nov 11 '22 08:11

Dave Thieben


Hope the following examples helps you.

Try to decorate your controller with

[Produces("application/json")]
[Route("api/[controller]")]

Since you din't show your controller name I will give you a fictitious full working example

controller

[Produces("application/json")]
[Route("api/[controller]")]    
public class DashBoardLayoutApi : Controller
{
    public DashBoardLayoutApi()
    { }

    [HttpPost]
    public void Post([FromBody] LoginViewModel data)
    { }
}

C# viewmodel

public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

HTML/JS

<script>
    var data = {
        Email: 'Test',
        Password: 'Test',
        RememberMe: true
    };

    $("#test").click(function() {
        $.ajax({
            url: '/api/DashBoardLayoutApi',
            type: 'POST',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),                   
        });
    }
</script>
<button id="test"> Save Layout</button>

Results

enter image description here enter image description here

like image 40
hidden Avatar answered Nov 11 '22 10:11

hidden


In my case, adding [Produces("application/json")] did nothing, but adding the [FromBody] attribute to the parameter is what did the trick!

like image 3
adam0101 Avatar answered Nov 11 '22 08:11

adam0101


The hidden's answer is great. However, I still had empty model in C# controller, even after I implemented hidden's approach in my application. After digging around a bit I found that the issue was in incorrect client model created in JS code, which cannot be deserialized on the server (null can not be converted to type Guid).

For some reason, model binder does not throw exceptions in such cases: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

When a parameter is bound, model binding stops looking for values with that name and it moves on to bind the next parameter. If binding fails, MVC does not throw an error. You can query for model state errors by checking the ModelState.IsValid property.

So, check the ModelState.IsValid property in C# controller to make sure you passed valid model and maybe consider using custom model binder to catch model binding errors and log them.

like image 1
Keymatic Avatar answered Nov 11 '22 08:11

Keymatic