我有一个 C# WebAPI 操作。我正在尝试使用 React 向它发布一个字符串(但一个 json 字符串化字符串)。
出于某种原因,当内容类型为应用程序/json 时,我得到了 405 Method Not Allowed。Urlencoded 确实进入 PostTransaction,但 body 始终为空。我需要更改什么才能在 PostTransaction 中获取 json?
网络配置
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
WebApiConfig
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
C# WebAPI
[HttpPost]
[ActionName("PostTransaction")]
public string PostTransaction([FromBody] string body, string task, int key, string filters, string options)
{
// body is null from react when content type is urlencoded, but correct from jquery post
string returnString = "no data found";
if (body != null) {
returnString = body.ToString();
}
return returnString;
}
反应
var dataToSend = JSON.stringify({ param1: "value1", param2: "value2"});
fetch('http://localhosturl/PostTransaction',
{
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: dataToSend
})
.then(response => {
}
jQuery 帖子
var dataToSend = JSON.stringify({ param1: "value1", param2: "value2"});
$.post('http://localhosturl/PostTransaction', { '': dataToSend }).done(function (data) {
console.debug(data); // returned data from Web API
});
谢谢