[英]how to return specific error message
I have WebAPI based project. 我有基于WebAPI的项目。 It has an API for user registration. 它具有用于用户注册的API。 RegistrationModel looks as below. RegistrationModel如下所示。
public class RegistrationTO
{
[Required(ErrorMessage="Email required")]
public string Email { get; set; }
[Required(ErrorMessage="Name required")]
public string Name { get; set; }
[Required(ErrorMessage="Surname required")]
public string Surname { get; set; }
}
API API
public string Post([FromBody]RegistrationTO model)
{
if (ModelState.IsValid)
{
//actual stuff
}
else
{
return "all * marked fields are required";
}
}
My requirement if model have Email as null, I should return message "email required", if Name is null then "Name required" & so on. 我的要求是,如果模型的Email为null,则应返回消息“ email required”,如果Name为null,则返回“ Name required”,依此类推。
Yes,one patchy way would be :- 是的,一种修补方式是:-
public string Post([FromBody]UserRegistrationTO model)
{
if (ModelState.IsValid)
{
//actual stuff
}
else
{
if(model.Email == null)
return "Email required";
else if(model.Name == null)
return "name required"; // & so on.
}
}
Is there any other simple way to do this?? 还有其他简单的方法吗?
try do that: 尝试这样做:
if (ModelState.IsValid)
{
// do something
}
else
return "The following errors happen: \n" +
ModelState.SelectMany(s => s.Value.Errors)
.Select(s => s.ErrorMessage)
.Aggregate((seed, currentValue) => seed += "\n" + currentValue);
I hope it can help you. 希望对您有所帮助。
You can do this at the view itself. 您可以在视图本身上执行此操作。
For individual properties : 对于单个属性:
@Html.ValidationMessageFor(x => x.Email, null, new { @class = "text-danger" })
and for all failed validation 对于所有失败的验证
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger">
@Html.ValidationSummary(false)
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.