我有一个具有对象类型
输入的操作方法,如下所示:
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")
//??!??!!??!?!?!?!??!
}
}
}
在此方法中,我首先将输入转换为我的 ViewModel,然后验证它。现在我想返回我在模型注释上设置的验证错误。 我怎样才能做到这一点?
我的 View 模型:
public class A
{
[Required(ErrorMessage = "Error1")]
string Phone;
.
.
.
}
public class B
{
[Required(ErrorMessage = "You must fill this parameter")]
string Name;
.
.
.
}
最佳答案
这是一个有效的演示:
行动:
public JsonResult DoSomeThing([FromBody]object input,bool options)
{
var model = new Object();
if (options)
{
model = JsonConvert.DeserializeObject<A>(input.ToString());
}
else {
model = JsonConvert.DeserializeObject<B>(input.ToString());
}
string messages = "";
if (!TryValidateModel(model))
{
messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
}
return Json(messages);
}
型号:
public class A
{
[Required(ErrorMessage = "Error1")]
public string Phone { get; set; }
}
public class B
{
[Required(ErrorMessage = "You must fill this parameter")]
public string Name { get; set; }
}
关于c# - 验证 MVC 核心中的非输入模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63401761/