ASP.NET Core 3.0 [FromBody]字符串内容返回“无法将JSON值转换为System.String." [英] ASP.NET Core 3.0 [FromBody] string content returns "The JSON value could not be converted to System.String."

查看:2008
本文介绍了ASP.NET Core 3.0 [FromBody]字符串内容返回“无法将JSON值转换为System.String."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Core 3.0的ApiController上使用[FromBody]字符串内容将返回验证错误:

Using [FromBody] string content on an ApiController in ASP.NET Core 3.0 returns a validation error:

{"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
 "title":"One or more validation errors occurred.",
 "status":400,
 "traceId":"|9dd96d96-4e64bafba4ba0245.",
 "errors":{"$":["The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."]}}

当客户端发布内容类型为application/json

when the client post data with content-type : application/json

如何在.NET Core 3.0的api控制器中以字符串形式获取原始json数据?无需客户端更新其内容类型?

How do I get the raw json data as a string in my api controller in .NET Core 3.0? Without the client having to update its content type?

推荐答案

我必须编写一个自定义IInputFormatter以确保我的身体内容始终被解释为字符串.

I had to write a custom IInputFormatter to ensure my body content was always interpreted as a string.

我还处于无法更新所有API客户端的情况.

I also was in the situation where updating all of the API clients was infeasible.

以下内容将确保任何[FromBody]参数都将被解释为字符串,即使调用者未将它们括在引号中.

The following will ensure that any [FromBody] parameters will be interpreted as strings, even if they are not quote-wrapped by the caller.

public class JsonStringInputFormatter : TextInputFormatter
{
    public JsonStringInputFormatter() : base()
    {
        SupportedEncodings.Add(UTF8EncodingWithoutBOM);
        SupportedEncodings.Add(UTF16EncodingLittleEndian);

        SupportedMediaTypes.Add(MediaTypeNames.Application.Json);
    }

    public override bool CanRead(InputFormatterContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        return context.ModelType == typeof(string);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(
        InputFormatterContext context, Encoding encoding)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        using (var streamReader = new StreamReader(
            context.HttpContext.Request.Body,
            encoding))
        {
            return await InputFormatterResult.SuccessAsync(
                (await streamReader.ReadToEndAsync()).Trim('"'));
        }
    }
}

通过对正文的引号进行修整,可以使其与格式正确且用引号包裹的正文内容具有向前兼容性.

Trimming quotes from the body allows this to be forwards-compatible for body content that is correctly formatted and quote-wrapped.

请确保它已在您的启动公司中注册,且未使用System.Text.Json格式化程序:

Ensure that it is registered in your startup before the System.Text.Json formatter:

services.AddControllers()
    .AddMvcOptions(options =>
    {
        options.InputFormatters.Insert(
            0,
            new JsonStringInputFormatter());
    });

这篇关于ASP.NET Core 3.0 [FromBody]字符串内容返回“无法将JSON值转换为System.String."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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