当内容类型为文本/纯文本时,.NET Core 1.0 Web Api 将请求正文处理为 JSON

LLL*_*LLL 2 json content-type .net-core asp.net-core-webapi

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

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

我确定我需要做类似于这个(下面的代码)答案的事情,但我不知道如何在 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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

LLL*_*LLL 5

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

        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"));
                }
            });
            ...
         }
Run Code Online (Sandbox Code Playgroud)

编辑:我为 SNS 客户端 lambda制作了一个种子项目,它解析消息并确认订阅。