Reputation: 159
I have a WebAPI project (c#) and i test it with my page (Index.cshtml):
<html>
<head>
...
</head>
<body>
<script src="@Url.Content("~/Scripts/jquery-3.2.1.js")" type="text/javascript"></script>
<script type="text/javascript">
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);
}
});
}
</script>
<p>
<button onclick="GetData()">GetData</button>
</p>
</body>
</html>
This page call my method:
[HttpPost]
[ResponseType(typeof(IEnumerable<СompositeType>))]
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.
Upvotes: 3
Views: 5847
Reputation: 159
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<СompositeType>))]
public HttpResponseMessage Test(string cox, [FromBody] Test str)
{
...
}
The third. I added a new class:
public class Test
{
public string str { set; get; }
}
Upvotes: 1