给一个 ASP.NET Core Web API 发送 Content-Type 为 text/plain
的请求时,出现错误:
HTTP/1.1 415 Unsupported Media Type
请问如何解决?
Controller 加了 [ApiController]
就会出现这个问题
通过自己实现 TextPlainInputFormatter 解决了
public class TextPlainInputFormatter : TextInputFormatter
{
private readonly string _separator;
public TextPlainInputFormatter(string separator = "\n")
{
_separator = separator;
SupportedMediaTypes.Add("text/plain");
SupportedEncodings.Add(Encoding.UTF8);
}
protected override bool CanReadType(Type type)
{
return type == typeof(string)
|| typeof(IEnumerable<string>).IsAssignableFrom(type);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
using var reader = context.ReaderFactory(context.HttpContext.Request.Body, encoding);
if (context.ModelType == typeof(string))
{
return await InputFormatterResult.SuccessAsync(reader.ReadToEndAsync());
}
else if (context.ModelType.IsAssignableTo(typeof(IEnumerable<string>)))
{
if (_separator == "\n")
{
var model = new List<string>();
while (true)
{
var line = await reader.ReadLineAsync();
if (line == null) break;
model.Add(line.Trim());
}
return await InputFormatterResult.SuccessAsync(
context.ModelType.IsArray ? model.ToArray() : model);
}
else
{
var model = (await reader.ReadToEndAsync()).Split(_separator);
return await InputFormatterResult.SuccessAsync(
context.ModelType == typeof(List<string>) ? model.ToList() : model);
}
}
return await InputFormatterResult.FailureAsync();
}
}
Program 中注册这个 TextPlainInputFormatter
builder.Services.AddControllers(options =>
{
options.InputFormatters.Add(new TextPlainInputFormatter());
});
那可不可以发送Content-Type 为 application/json 的请求 (/ω\)
需要通过 curl 命令发送一组搜索关键词(一行一个关键词)到服务端,不是 json 格式
curl -v --data-binary @terms.txt -H 'Content-Type:text/plain' localhost:5005/home/search
出现这个问题是由于对于 text/plain 没有对应的 InputFormatter
– dudu 2年前