ASP.NET Core 3.1 Web Api HttpPost操作参数无法接收AXIOS应用程序/json HttpPost传递数据 [英] ASP.NET Core 3.1 Web Api HttpPost Action parameter can't receive axios application/json HttpPost passing data
本文介绍了ASP.NET Core 3.1 Web Api HttpPost操作参数无法接收AXIOS应用程序/json HttpPost传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以前使用的是控制器,而不是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) {
//...
测试结果
这篇关于ASP.NET Core 3.1 Web Api HttpPost操作参数无法接收AXIOS应用程序/json HttpPost传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文