当内容类型为text / plain时,.NET Core 1.0 Web Api处理请求体为JSON

时间:2017-08-05 08:40:22

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

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

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

我确定我需要做一些与this(下面的代码)相似的回答,但我不知道如何在网络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;
            }
        }
    }

1 个答案:

答案 0 :(得分:4)

I made it work by adding the text/plain content-type to the JsonInputFormatter in Startup.cs ConfigureServices() method, like so:

        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"));
                }
            });
            ...
         }

Edit: I made a seed project for the SNS client lambda, that parses the message and confirms the subscription out the box.