Click here to Skip to main content
14,927,127 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to post json data to web api 2 but i’m receiving error 415- unsupported media type.

c# class.
C#
public class Person{

public int Id {get; set}

public string Name {get; set;}
}




... and below is the action of the webApi controller

C#
//


[httpPost]
public IActionResult PostAddPerson([FromBody] Person person)
{
 // processing here

}



... json from client
JavaScript
{
  "Id":1,
 "name":"Person1"
}


What I have tried:

I changed
C#
[FromBody]
which always returns null for 'person' to
C#
[FromForm]
, and when i check the parameter 'person' all properties are of default values only and not that from the client side.

i changed content-type to 'application/json' at client side and still nothing changed
Posted
Updated 23-Oct-20 0:57am
v2
Comments
ZurdoDev 5-Jun-19 15:11pm
   
That error is an http error usually indicating your content-type is incorrect.

FromBody should work, but your JSON is invalid: valid JSON has double quotes around keys, and double quotes around strings. Try this JSON:
{
  "personId": 1,
  "name": "Person1"
}
I also don't know if it will work to have personId in your JSON but Id in your Person class?
   
Comments
kwaku Emma 5-Jun-19 10:45am
   
Thank you. the previous json was a mistake. I've tried your suggestion but still the same error is thrown.
Thomas Daniels 5-Jun-19 11:13am
   
I'm not sure then... you could try to have your JSON keys start with a capital letter like in your C# code (although I think it should be parsed case-insensitively, but it's worth a try).

Or check the Content-Encoding header that your client sends - that header may also cause a 415.

If the issue is neither of these two then I'm afraid I'm out of ideas.
kwaku Emma 5-Jun-19 19:51pm
   
thanks for your help so far. The problem was with the headers. Refer to this site for how to set Content-Type. What is on Mozilla's site on how to set 'Content-Type' header to 'application/json' was not working for me.
You need to add this code in your Startup.cs inside ConfigureServices
services.AddControllers().AddNewtonsoftJson();
   
Comments
Richard Deeming 27-Oct-20 11:59am
   
The question refers to WebAPI 2. Your answer applies to .NET Core, and doesn't explain why you think the built-in JSON library isn't up to the task of deserializing such basic JSON.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900