我以前使用的是控制器,而不是ApiController,今天我尝试使用ApiController,发现了以下问题。
ASP.NET核心Web Api HttpPost操作参数无法接收AXIosapplication/json
POST传递数据
ASP.NET核心API代码
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Post(string json)
{
return this.Ok();
}
}
前端
var json = '{"json_data":"{"value":"hello world"}';
axios.post('Test', {"json": json})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
实际需求
Accept:application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Content-Type: application/json;charset=UTF-8
Request Payload :
{"json_data":"{"value":"hello world"}
实际动作json参数数据为null
预期接收数据:{"json_data":"{"value":"hello world"}
更新
我尝试了以下代码,得到rawValue值={"json_data":"{"value":"hello world"}
,但json值=null
[HttpPost]
public async Task<IActionResult> Post(string json)
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
string rawValue = await reader.ReadToEndAsync();
}
}
公共异步任务发布(字符串json)
如果要从前端使用数据进行HTTP请求并将其正确绑定到字符串类型操作参数,您可以尝试实现和使用自定义纯文本输入格式化程序。
public class TextPlainInputFormatter : TextInputFormatter
{
public TextPlainInputFormatter()
{
SupportedMediaTypes.Add("text/plain");
SupportedEncodings.Add(UTF8EncodingWithoutBOM);
SupportedEncodings.Add(UTF16EncodingLittleEndian);
}
protected override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
string data = null;
using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
{
data = await streamReader.ReadToEndAsync();
}
return InputFormatterResult.Success(data);
}
}
配置和添加自定义格式化程序支持
services.AddControllers(opt => opt.InputFormatters.Insert(0, new TextPlainInputFormatter()));
前台代码
const headers = {
'Content-Type': 'text/plain'
};
var json = '{"json_data":"{"value":"hello world"}';
axios.post('test', json, { headers: headers })
.then(function (response) {
//...
测试结果