首页 > 解决方案 > how to convert the JSON object into form data and send it as Data to web api fetch

问题描述

I am having a json object in the client side and i want to receive that in the Web api controller like controllerContext.HttpContext.Request["Name"] How to send that Json from web API.

The Data expected as "name=abc&type=xyz" for the fetch api. How to convert the JSON object

 {
name: abc,
type:xyz
}

below code is not working

{
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json'
            },
            credentials: 'same-origin',
            body: JSON.stringify({
            name:abc,
            type:xyz
            })
          };
          
Replacing body and header as below works fine

 body: "name=abc&type=xyz"
 headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
       }

How to convert the Json object as above and what is the reason for that .?

标签: javascriptajaxreactjsreact-nativeasp.net-web-api

解决方案


我不知道 ASP.NET,但我相信有一种方法可以将数据类型配置为 JSON 而不是 form-urlencoded。或者您需要自定义服务器解析数据的方式。

如果无法更改为 application/json。您可以使用querystring包将您的 JSON obj 字符串化为 urlenconded 格式。


推荐阅读