如果你想获取客户端上报上来的原始 JSON ,除了读取请求流之外,还可以试试以下两个方法:
方法1:使用 dynamic 作为参数类型
该方法非常简单,且能保证得到的 JSON 格式是正确的。但会产生额外的消耗。
[HttpPost]
public void Post([FromBody] dynamic data)
{
//str 既是请求体的原文
string str = data.ToString();
}
方法2:使用自定义的 RawJsonBodyInputFormatter
该方法的优点是:避免了使用 dynamic 类型作为参数时产生的额外消耗。
缺点是:没有对 JSON 进行验证,且需要对应用程序进行一些改动。
首先,新建一个 RawJsonBodyInputFormatter :
public class RawJsonBodyInputFormatter : InputFormatter
{
public RawJsonBodyInputFormatter()
{
this.SupportedMediaTypes.Add("application/json");
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(content);
}
}
protected override bool CanReadType(Type type)
{
return type == typeof(string);
}
}
配置 MvcOptions :
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new RawJsonBodyInputFormatter());
});
这样你就可以在控制器中获取原始 JSON :
[HttpPost]
public IActionResult Post([FromBody]string value)
{
// value will be the request json payload
}










