ASP.NET Core 3.1 Web Api HttpPost方法接收axios的POST请求数据

本文主要介绍 ASP.NET Core 3.1 Web Api 中,前端通过axios执行POST请求提交application/json格式数据,后台通过HttpPost的API接口方法接收数据的方法,以及相关的示例代码。

1、axios请求提交数据

const headers = {
'Content-Type': 'text/plain'
};
var json = '{"json_data":"{\"value\":\"hello world\"}';
axios.post('test', json, { headers: headers })
.then(function (response) {alert(response)}

2、后台接收POST数据API

1)API方法

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Post([FromBody]string json)
{
return this.Ok();
}
}

2)使用自定义纯文本输入格式化器

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);
}
}

3)在ConfigureServices(IServiceCollection services) 中添加配置

services.AddControllers(opt => opt.InputFormatters.Insert(0, new TextPlainInputFormatter()));

推荐阅读
cjavapy编程之路首页