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