新建类TextPlainType,继承InputFormatter。
public class TextPlainType : InputFormatter
{
public TextPlainType() {
SupportedMediaTypes.Add("text/plain");
}
protected override bool CanReadType(Type type)
{
if (type == typeof(string) || type == typeof(DateTime)) {
return true;
}
else
{
return false;
}
}
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
object result;
using (var _reader = context.ReaderFactory(context.HttpContext.Request.Body, Encoding.UTF8)) {
result = _reader.ReadToEndAsync().Result;
}
if (context.ModelType == typeof(string)) {
return InputFormatterResult.SuccessAsync(Convert.ToString(result));
} else if (context.ModelType == typeof(DateTime)) {
return InputFormatterResult.SuccessAsync(Convert.ToDateTime(result));
}
else
{
throw new InvalidOperationException();
}
}
}
Program注册该类
builder.Services.AddControllers(
opt => opt.InputFormatters.Insert(0,new TextPlainType())
) ;
方法
[HttpPost]
public string Post([FromBody]string name)
{
string say = "我是" + name;
return say;
}
调用结果
参考: