javascript - C# 到 Javascript : What the equivalent of `new MultipartFormDataContent();`

标签 javascript c#

我有这个遗留的 C# 代码(我不懂 C#),我需要用 Javascript 编写相同的功能(我非常了解 JS)。所以 C# 代码是:

static JavaScriptSerializer serializer = new JavaScriptSerializer();
MultipartFormDataContent content = new MultipartFormDataContent();
item item_1 = new item
{
    a = 'a',
    b = 'b'
};
string jsonPayload = serializer.Serialize(item_1);
var stringContent = new StringContent(jsonPayload);
stringContent.Headers.ContentType.MediaType = "text/json";
content.Add(stringContent, item_1.GetType().Name);
// then it makes a network request

如果我必须做出最好的猜测,这就是我认为它会在 JS 中做的事情,尽管我一定有点偏离,因为 api 正在返回 415 Unsupported Media Type:

const item_1 = {
    a: 'a',
    b: 'b'
}; 
const jsonPayload = JSON.stringify(item_1); 
const formData = new FormData(); 
formData.set('data', jsonPayload); 
fetch('/some_api/endpoint',{
    headers: {
        "Content-Type":"text/json"
    },
    method: 'POST',
    body: formData
});

如果您需要更多信息,或者对如何改进帖子有任何疑问或建议,请发表评论!感谢您的帮助!

最佳答案

为什么要创建 FormData 对象?我认为您只想将内容作为 JSON 发送;

const item_1 = {
    a: 'a',
    b: 'b'
}; 
const jsonPayload = JSON.stringify(item_1); 
fetch('/some_api/endpoint',{
    headers: {
        "Content-Type":"text/json"
    },
    method: 'POST',
    body: jsonPayload 
});

从这个文档页面 (https://developer.mozilla.org/en-US/docs/Web/API/FormData) 看来,这不是 JSON 内容类型;

It uses the same format a form would use if the encoding type were set to "multipart/form-data".

关于javascript - C# 到 Javascript : What the equivalent of `new MultipartFormDataContent();` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860114/

相关文章:

c# - 如何始终根据我的轴方向移动我的对象?

javascript - Highcharts 解析的深入分析未显示在页面上,但显示在控制台中

Javascript 使用 File.Reader() 逐行读取

c# - 以 Windows 服务用户身份运行进程失败并拒绝访问?

c# - 默认构造函数创建的 `Dictionary`是否使用哈希码?

c# - 性能计数器输入字符串的格式不正确 C#

javascript - Leaflet Mouseout 调用 MouseOver 事件

javascript - Bing Maps API v8 - 图钉 SVG URI 图像

javascript - 选择器上的 Jquery 单击事件返回子作为目标

C#图像扫描像素颜色