简体   繁体   English

从React将Json发布到C#WebApi

[英]Posting Json to C# WebApi from React

I have a C# WebAPI action. 我有一个C#WebAPI操作。 I'm trying to post a string (but a json stringified string) to it using React. 我正在尝试使用React向其发布一个字符串(但是json字符串化字符串)。

For some reason I'm getting a 405 Method Not Allowed when the content type is aopplication/json. 由于某种原因,当内容类型为aopplication / json时,我得到了405 Method Not Allowed。 Urlencoded does get into PostTransaction, but body is always null. Urlencoded确实进入了PostTransaction,但是body始终为null。 What do I need to change to be able to get json in PostTransaction? 我需要更改什么才能在PostTransaction中获取json?

WebConfig WebConfig

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

WebApiConfig WebApiConfig

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

C# WebApi 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;
}

React 应对

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

Thanks 谢谢

So the reason for the difference, is that I needed to convert the object in React, to a string, then stringify it again. 因此产生差异的原因是,我需要将React中的对象转换为字符串,然后再次对其进行字符串化。

My original post did do this, but at the same time I changed it from urlencoded to application/json, if I'd just originally changed it (see history) to application/json without removing the second stringify, it would have worked ok. 我的原始帖子确实做到了这一点,但是同时我将其从urlencoded更改为application / json,如果我只是将它(请参阅历史记录)最初更改为application / json而又不删除第二个stringify,那应该可以。

body: JSON.stringify(JSON.stringify(dataToSave))

This is so that when it's actually posted, it still has the escaped quotes. 这样一来,当它实际发布时,它仍然具有转义的引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM