问题描述
我需要使用的供应商 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!