【发布时间】:2020-12-03 16:36:29
【问题描述】:
我有一个带有object type 输入的操作方法,如下所示:
public async Task<IActionResult> DoSomeThing([FromBody]object input, bool options)
{
if (options == true)
{
var castedInput = (A) input;
if (TryValidateModel(castedInput))
{
// do some thing
}
else
{
//return validation Errors;
//forexample:return Error("Error1")
//??!??!!??!?!?!?!??!
}
}
else
{
var castedInput = (B)input;
if (TryValidateModel(castedInput))
{
// do some thing
}
else
{
//return validation Errors;
//forexample:return Error("You must fill this parameter")
//??!??!!??!?!?!?!??!
}
}
}
在此方法中,我首先将 Input 转换为我的 ViewModel,然后对其进行验证。现在我想返回我在模型注释上设置的验证错误。 我该怎么做?
我的视图模型:
public class A
{
[Required(ErrorMessage = "Error1")]
string Phone;
.
.
.
}
public class B
{
[Required(ErrorMessage = "You must fill this parameter")]
string Name;
.
.
.
}
【问题讨论】:
-
不知道你的输入应该是什么形状是一个非常糟糕的主意。每种方法都应该有一个不同的、已定义的模型。
-
当你使用
[FromBody]object input,并且在调试var castedInput = (A) input;时,你会得到一个类似System.InvalidCastException: Unable to cast object of type 'System.Text.Json.JsonElement' to type 'xxx.A'.的错误,所以你需要在你的action中将Object定义为A或B。例如:@ 987654327@,public async Task<IActionResult> DoSomeThing2([FromBody]B input) -
感谢您的回答,我知道此方法存在问题,但总的来说,我想获得未输入模型的验证错误消息。例如
castedInput模型错误消息对此没有意见?
标签: c# asp.net-mvc validation asp.net-core