首页 新闻 会员 周边

ASP.NET Core 发送 "text/plain" 请求时报错 "415 Unsupported Media Type"

-1
悬赏园豆:30 [已解决问题] 解决于 2022-07-17 16:10

给一个 ASP.NET Core Web API 发送 Content-Type 为 text/plain 的请求时,出现错误:

HTTP/1.1 415 Unsupported Media Type

请问如何解决?

问题补充:

Controller 加了 [ApiController] 就会出现这个问题

dudu的主页 dudu | 高人七级 | 园豆:31003
提问于:2022-07-16 21:58

出现这个问题是由于对于 text/plain 没有对应的 InputFormatter

dudu 1年前
< >
分享
最佳答案
0

通过自己实现 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());
});

参考:Custom formatters in ASP.NET Core Web API

dudu | 高人七级 |园豆:31003 | 2022-07-17 13:21
其他回答(1)
0

那可不可以发送Content-Type 为 application/json 的请求 (/ω\)

收获园豆:30
顾星河 | 园豆:7173 (大侠五级) | 2022-07-16 23:39

需要通过 curl 命令发送一组搜索关键词(一行一个关键词)到服务端,不是 json 格式

curl -v --data-binary @terms.txt -H 'Content-Type:text/plain' localhost:5005/home/search
支持(0) 反对(0) dudu | 园豆:31003 (高人七级) | 2022-07-17 09:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册