You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将JSON字符串从HTML表单发送至Web API控制器问题

问题原因分析
  • 415错误:前端未设置Content-Type: application/json,jQuery的$.ajax默认用application/x-www-form-urlencoded格式发送请求,后端无法通过[FromBody]解析该格式的请求体。
  • 移除[FromBody]后400错误:此时后端期望从表单字段中获取jsonString参数,但你发送的是纯JSON字符串,不存在对应字段,因此触发必填校验错误。
解决方案

方案一:用强类型实体接收(推荐)

这是REST API的常规实现方式,更易维护和扩展:

  1. 定义对应的数据模型:
public class RequestModel
{
    public string application_name { get; set; }
    public string asset_type { get; set; }
}
  1. 修改Action方法:
[HttpPost]
public void Post([FromBody] RequestModel model)
{
    // 直接使用model.application_name、model.asset_type即可
}
  1. 前端给$.ajax添加contentType配置:
$.ajax({
    url: 'https://localhost:7273/WeatherForecast',
    type: 'POST',
    data: stringifyObj,
    contentType: 'application/json', // 关键:告知后端请求体为JSON格式
    dataType: 'json',
    success: function (response) {
        console.log(response);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest.responseText)
    }
});

方案二:保持后端接收string类型

如果必须以原始JSON字符串形式接收:

  1. 后端代码保持不变:
[HttpPost]
public void Post([FromBody] string jsonString)
{
}
  1. 前端需对JSON字符串做二次序列化(包裹成JSON字符串值),同时添加contentType:
// 将原JSON对象字符串再次转义为JSON格式的字符串值
var wrappedJson = JSON.stringify(stringifyObj);
$.ajax({
    url: 'https://localhost:7273/WeatherForecast',
    type: 'POST',
    data: wrappedJson,
    contentType: 'application/json',
    dataType: 'json',
    success: function (response) {
        console.log(response);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest.responseText)
    }
});

因为[FromBody] string要求请求体是一个JSON字符串值,而非JSON对象,所以需要对原始JSON对象做二次序列化处理。

重点提醒

不要混淆contentType和dataType:contentType是你发送请求的格式,dataType是预期后端返回的格式,设置请求格式必须使用contentType。

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:30:39