WebAPI,[FromBody]字符串,application / json,错误415(不支持的媒体类型)

时间:2018-05-23 08:12:22

标签: c# ajax asp.net-web-api

我有一个WebAPI项目(c#),我用我的页面(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>

此页面调用我的方法:

[HttpPost]
[ResponseType(typeof(IEnumerable<СompositeType>))]
public HttpResponseMessage Test(string cox, [FromBody] string str)
{
   ...    
}

我收到错误:415“不支持的媒体类型”。我读到了这个错误,有人在说contentType: 'application/json, charset=utf-8'将解决问题。我知道属性[FromBody]调用contentType: 'application/json'进行转换,但我不知道为什么我有错误415.

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但它有点作弊。 (我想说:“谢谢!)”,因为 答案)。

第一个。我改变了这个:

 data: JSON.stringify({"str":"Hello!!!"}),
 contentType: 'application/json; charset=utf-8',

第二个。我改变了这个:

[HttpPost]
[ResponseType(typeof(IEnumerable<СompositeType>))]
public HttpResponseMessage Test(string cox, [FromBody] Test str)
{
   ...    
}

第三次。我添加了一个新类:

public class Test
{
    public string str { set; get; }
}