ASP.NET MVC中POST请求传值至Controller参数为null的解决方法
ASP.NET MVC POST请求参数为null的解决办法
问题场景
前端通过fetch发送POST请求到ASP.NET MVC的Controller,后端方法参数始终为null,使用[FromBody]或[FromForm]均无效,返回结果为{ "got": null }。
后端C#代码
using Microsoft.AspNetCore.Mvc; namespace Tester.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [HttpPost] public string SendData1([FromBody]string data) { // data is null! return Newtonsoft.Json.JsonConvert.SerializeObject(new { got = data }); } } }
前端Index.cshtml代码
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about building Web apps with ASP.NET Core.</p> </div> <script> window.addEventListener('DOMContentLoaded', ()=>{ document.getElementById('send').addEventListener('click', ()=>{ const text = document.getElementById('text').value; const path = window.location.origin; fetch(path + '/Home/SendData1', { method: 'post', credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ data: text }) }) .then(x => x.json()) .then(console.log); }) }) </script> <div> <input type="text" id="text" /> <button type="button" id="send">Send</button> </div>
原因分析
- 使用
[FromBody]接收string类型参数时,ASP.NET Core期望请求体是纯JSON字符串(如"hello world"),而非包含键值对的JSON对象(如{"data":"hello world"}),因此模型绑定失败,参数为null。 - 使用
[FromForm]时,前端发送的是JSON格式数据,而非form-data或x-www-form-urlencoded格式,同样无法完成绑定。
解决方法
方法一:修改前端请求体为纯字符串
保持后端代码不变,将前端fetch的body改为直接序列化输入的文本,而非对象:
fetch(path + '/Home/SendData1', { method: 'post', credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify(text) // 直接序列化字符串,而非{ data: text } })
方法二:后端定义实体类接收参数
如果不想修改前端请求,可在后端创建对应的数据模型类,用于接收JSON对象:
// 新增实体类 public class DataRequestModel { public string Data { get; set; } } // 修改Controller方法 [HttpPost] public string SendData1([FromBody]DataRequestModel model) { return Newtonsoft.Json.JsonConvert.SerializeObject(new { got = model.Data }); }
方法三:使用[FromForm]并修改前端发送form数据
若要使用[FromForm],需将前端请求改为发送表单格式数据:
fetch(path + '/Home/SendData1', { method: 'post', credentials: "include", // 无需手动设置Content-Type,浏览器会自动添加正确的multipart/form-data头 body: (() => { const formData = new FormData(); formData.append('data', text); return formData; })() })
同时后端方法修改为:
[HttpPost] public string SendData1([FromForm]string data) { return Newtonsoft.Json.JsonConvert.SerializeObject(new { got = data }); }
内容的提问来源于stack exchange,提问作者Ramzi Khahil
相关产品推荐
相关产品推荐

