【问题标题】:.NET Core 1.0 Web Api processing request body as JSON when content-type is text/plain当内容类型为文本/纯文本时,.NET Core 1.0 Web Api 将请求正文处理为 JSON
【发布时间】:2018-01-13 04:02:33
【问题描述】:

我需要使用的供应商 API 发送一个 POST 请求,内容类型为:text/plain 和正文中的 JSON。

如何在 .net core 1.0 web api 中解析它?

我确定我需要做类似于this(下面的代码)答案的事情,但我不知道如何在 web api 中。

    public class RawContentTypeMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {
            switch (contentType.ToLowerInvariant())
            {
                case "text/plain":
                case "application/json":
                    return WebContentFormat.Json;
                case "application/xml":
                    return WebContentFormat.Xml;
                default:
                    return WebContentFormat.Default;
            }
        }
    }

【问题讨论】:

    标签: json .net-core content-type asp.net-core-webapi


    【解决方案1】:

    我通过在 Startup.cs ConfigureServices() 方法中将 text/plain 内容类型添加到 JsonInputFormatter 使其工作,如下所示:

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc(config =>
                {
                    foreach (var formatter in config.InputFormatters)
                    {
                        if (formatter.GetType() == typeof(JsonInputFormatter))
                            ((JsonInputFormatter)formatter).SupportedMediaTypes.Add(
                                MediaTypeHeaderValue.Parse("text/plain"));
                    }
                });
                ...
             }
    

    编辑:我为 SNS 客户端 lambda 创建了一个 seed 项目,它解析消息并开箱确认订阅。

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2020-02-18
      • 1970-01-01
      • 2011-08-20
      • 2021-11-03
      • 2016-09-27
      • 2011-12-25
      • 2018-05-11
      • 2018-09-03
      相关资源
      最近更新 更多