热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开发笔记:“尝试调用控制器端点时无法将JSON值转换为System.String”

篇首语:本文由编程笔记#小编为大家整理,主要介绍了“尝试调用控制器端点时无法将JSON值转换为System.String”相关的知识,希望对你有一定的参考价值。

篇首语:本文由编程笔记#小编为大家整理,主要介绍了“尝试调用控制器端点时无法将JSON值转换为System.String”相关的知识,希望对你有一定的参考价值。



我一直在尝试创建一个简单的API,我设法使Get正常工作,但是每当我尝试使用PostPut时,我都无法使其正常工作。我正在尝试发布/放置JSON并将其作为字符串在我的控制器中获取。我正在使用Postman和Insomnia进行测试(由于我是在本地运行的,因此我转为同时使用SSL验证)。这是我的控制器:

[Route("backoffice/[controller]")]
[ApiController]
public class AddQuestionController : ControllerBase
{
private IQuestionRepository _questionRepository;
public AddQuestionController(IQuestionRepository questionRepository)
{
_questiOnRepository= questionRepository ?? throw new ArgumentNullException(nameof(questionRepository));
}
[ProducesResponseType((int)System.Net.HttpStatusCode.OK)]
[HttpPost]
public async Task AddQuestion([FromBody] string question)
{
Question q = JsonConvert.DeserializeObject(question);
await Task.Run(() => _questionRepository.InsertOne(q));
return Ok();
}
}

postman

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

所以我当时想这是因为邮递员中的Json格式。但是后来我尝试了text格式这发生了:

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "|a0b79873-4e41e975d19e251e."
}

而且每次它甚至都没有到达控制器的第一行时。有人可以告诉我我在这里做错了什么吗?是我的控制器吗?这是我使用邮递员的方式吗?

答案

模型绑定器无法将发送的数据映射/绑定到控制器参数

您的操作需要来自请求正文的简单字符串

public async Task AddQuestion([FromBody] string question)

但是您发送了一个复杂的对象

{ "test" : "test" }

如果属性名称匹配,则可能已匹配

例如

{ "question" : "test" }

因为模型绑定器在匹配参数时会考虑属性名称。

如果要接收原始字符串,则需要发送有效的原始JSON字符串

"{ "test": "test "}"

已正确转义。

另一个选项是对参数使用复杂的对象

class Question {
public string test { get; set; }
//...other properties
}

与预期数据匹配

public async Task AddQuestion([FromBody] Question question) {
string value = question.test;
//...
}

参考Model Binding in ASP.NET Core


推荐阅读
author-avatar
-起司Cheese-
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有