.net6 接收json数据 Controller http post
要添加这两个包
前端ajax请求
function tst() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/HelloWorld/Welcome",
data: JSON.stringify({ "ID":1,"name": "haha" }),
dataType: "json",
success: function (data) {
alert(data);
}
});
};
关键在contentType 和JSON.stringify 如果这2两个没加上后台还是接收不到的!
contentType: “application/json”,
后台接收加上一个 [FromBody]
后台示例
public class test
{
public int ID { get; set; }
public string name { get; set; }
}
public string Welcome([FromBody]test ha)
{}
后台完整代码
using DotNetWebApp0514a.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Web;
namespace DotNetWebApp0514a.Controllers
{
public class UserData
{
public string id { get; set; }
public string name { get; set; }
}
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public String getQrCode(Object data)
{
mylog("jsonData" + data);
String ticket = "";
return ticket;
}
public void mylog(String str, String str1="")
{
System.Diagnostics.Debug.WriteLine(str, str1);
}
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
mylog("进入 Index");
return View();
}
public IActionResult Privacy()
{
mylog("进入 Privacy");
return View();
}
// 能自动装配form表单数据 theJson(StuData stu)
// 但不能自动装配json,要这样 theJson([FromBody]UserData stu)
public List<UserData> theJson([FromBody]UserData stu)
{
String str = JsonConvert.SerializeObject(stu);
System.Diagnostics.Debug.WriteLine("收到:"+str);
// Request.QueryString["ssss"].ToString();
List<UserData> dataList = new List<UserData>() {
new UserData {id="1",name="asd" },
};
String theJson = JsonConvert.SerializeObject(dataList);
System.Diagnostics.Debug.WriteLine("theJson:" + theJson);
return dataList;
// 原文链接:https://blog.csdn.net/wesleysd/article/details/123065099
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
System.Diagnostics.Debug.Write("进入 Error");
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}