[英]How to determine the type of Validation Error on Asp.Net Identity using Model Validation
I'm using Asp.Net Identity 2.0, Web Api 2 and .Net Framework 4.5. 我正在使用Asp.Net Identity 2.0,Web Api 2和.Net Framework 4.5。
I've implemented a validation filter for Web Api which captures all the model validation errors. 我为Web Api实现了一个验证过滤器,该过滤器捕获了所有模型验证错误。
Asp.net Identity provides text errors for each model validation error but it doesn't provide a way to know the type of validation error. Asp.net Identity为每个模型验证错误提供文本错误,但没有提供知道验证错误类型的方法。 For example I don't need the text error "The phone parameter is required" but I do need to know that the error is a "Required" validation error or any attribute I had put on top of the property.
例如,我不需要文本错误“手机参数是必需的”,但我确实需要知道该错误是“必需的”验证错误或我在属性顶部设置的任何属性。
Example: 例:
Class MyModel
{
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Phone {get; set;};
}
How can I know if the ModelState
contains a RequiredError
or a StringLenght
error without reading the text error? 我如何才能知道
ModelState
包含RequiredError
或StringLenght
错误而不读取文本错误?
You can read it directly from the property: 您可以直接从属性中读取它:
using System.Reflection;
var modelStateProperties = typeof(MyModel).GetProperties().Where(p => ModelState.Keys.Any(k => k == p.Name));
foreach (var property in modelStateProperties)
{
// Found properties with errors in them
var attrs = properties.GetCustomAttributes();
// attrs now has the list of attributes, i.e., Required, StringLength, etc.
}
ModelState doesn't have what you need, the Model does. ModelState没有您需要的东西,而Model有。 So, you have to find properties in
MyModel
with errors and loop through each property attribute. 因此,您必须在
MyModel
中MyModel
有错误的属性, MyModel
遍历每个属性属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.