.NET Core 1.0 Web Api processing request body as JSON when content-type is text/plain

你。 提交于 2019-12-01 08:09:54

问题


A vendor API I need to use is sending a POST request with content-type: text/plain and JSON in the body.

How do I parse it in .net core 1.0 web api?

I'm sure I need to do something similar to this (code below) answer, but I don't know how in 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;
            }
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/45519950/net-core-1-0-web-api-processing-request-body-as-json-when-content-type-is-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!