当内容类型为文本/纯文本时,.NET Core 1.0 Web Api 将请求正文处理为 JSON [英] .NET Core 1.0 Web Api processing request body as JSON when content-type is text/plain

查看:28
本文介绍了当内容类型为文本/纯文本时,.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 内容类型添加到 JsonInputFormatter 中使其工作>Startup.cs ConfigureServices() 方法,像这样:

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 制作了一个 seed 项目, 解析消息并确认订阅.

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

这篇关于当内容类型为文本/纯文本时,.NET Core 1.0 Web Api 将请求正文处理为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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