I have a WebAPI project (c#) and i test it with my page (Index.cshtml):
...
function GetData() {
$.ajax({
url: "http://localhost:0000/api/test/test/cox/Test",
type: 'POST',
dataType: 'json',
data: JSON.stringify("Hello!!!"),
crossDomain: true,
processData: false,
contentType: 'application/json, charset=utf-8',
headers: { User: "test", Password: "test" },
success: function (q, w, e) {
alert(JSON.stringify(q));
},
error: function (q, w, e) {
alert("error: " + w);
}
});
}
GetData
This page call my method:
[HttpPost]
[ResponseType(typeof(IEnumerable))]
public HttpResponseMessage Test(string cox, [FromBody] string str)
{
...
}
and i get the error: 415 "Unsupported Media Type". I read about this error and somebody is talking that contentType: 'application/json, charset=utf-8' will solve the problem. I know that attribute [FromBody] call to contentType: 'application/json' for transformation , but i don't undestand why i have the error 415.
Talk1:
It should be "application/json; charset=utf-8" (note ";" instead of ",")
Talk2:
It is don't work, i get error 400 (Bad Request).
Talk3:
Maybe, but specific problem in your question is now solved, now you have another problem.
Talk4:
I don't think so, because if i write data: JSON.stringify(), i call method Test.
Talk5:
Why using JSON for non object data? I also think you should try using data: JSON.stringify({ str: "Hello!!!"}) so the httphandler can match parameter name (I'm not shure cause I ususally use models for transfering data to/from APIs)...
Solutions1
I found a solution, but it is a little cheat. (I want to say: "Thank you!)", for
the answers).
The first. I changed this:
data: JSON.stringify({"str":"Hello!!!"}),
contentType: 'application/json; charset=utf-8',
The second. I changed this:
[HttpPost]
[ResponseType(typeof(IEnumerable))]
public HttpResponseMessage Test(string cox, [FromBody] Test str)
{
...
}
The third. I added a new class:
public class Test
{
public string str { set; get; }
}