当content-type为text/plain时,.NET Core 1.0 Web Api将请求主体作为JSON [英] .NET Core 1.0 Web Api processing request body as JSON when content-type is text/plain

查看:251
本文介绍了当content-type为text/plain时,.NET Core 1.0 Web Api将请求主体作为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何在.net core 1.0 Web API中解析它?

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

我确定我需要做类似于(下面的代码)的操作,但是我不需要知道如何使用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;
            }
        }
    }

推荐答案

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

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

编辑:我为SNS客户端lambda创建了一个种子项目,该邮件将解析邮件并确认订阅.

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

这篇关于当content-type为text/plain时,.NET Core 1.0 Web Api将请求主体作为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆