我正在尝试使用原始字符串参数编写操作。
此字符串将作为json动态解析,因此在编译时不知道json中的键。
我以这种方式声明了该方法:
[HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction([FromBody] string command)
{
var cmd = MyCqrsCommand(command);
return await Mediator.Send(cmd);
}
我用招摇叫的方法将参数显示为application / json
结果是这个
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|4e0e9c40-4036f8a9873ecac8.",
"errors": {
"$": [
"The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
]
}
}
我找到了两种不同的解决方案:
[HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction([FromBody] object command)
{ ... }
[HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction(string command)
{ ... }
使用对象不是很好,但是可以。 在uri中使用“字符串”有一些限制,所以我更喜欢前一个。
哪个是最好的解决方案?有没有一种方法可以将字符串插入声明为字符串而不是对象的正文中?
答案 0 :(得分:1)
使用JsonObject作为输入参数,而不是字符串和对象。
答案 1 :(得分:1)
哪个是最好的解决方案?
我愿意使用对象参数解决方案。
var picture = await ImagePicker.pickImage(source: ImageSource.camera);
从请求的屏幕截图我们可以看到,您已将 JSON对象 [HttpPost("MyAction")]
public async Task<ActionResult<long>> MyAction([FromBody] object command)
{ ... }
发送到{ "key": "value" }
方法。因此,您不应将参数声明为MyAction
。
有没有一种方法可以插入 正文中的字符串声明为字符串而不是对象?
如果希望使用“字符串”作为输入参数,则只需发送值的内容。
string