webapi html字符串,C#WebAPI,[FromBody]字符串,应用程序/ json,错误415(不受支持的媒体类型)...

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; }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值