我有一个域对象所有者。这有一些数据注释,将在web api post方法中使用以进行验证。
public class Owner
{
[Required(ErrorMessage ="Please select a title")]
public string Title { get; set; }
[Required(ErrorMessage = "First name is required")]
[MaxLength(100, ErrorMessage ="Too long")]
public string Firstname { get; set; }
[Required(ErrorMessage = "Last name is required")]
public string Lastname { get; set; }
public string PostalAddressStreet { get; set; }
public string PostalAddressSuburb { get; set; }
public string PostalAddressState { get; set; }
}现在,我需要在get请求中将此对象的验证规则(在数据注释中定义)发送到前端。我正在看this问题,它解释了如何在MVC中做到这一点。但无法在web api get方法中使用它。这就是我尝试过的。
[HttpGet]
[Route("GetOwnerDefinition")]
public string GetPetOwnerDefinition()
{
Owner owner = new Owner();
System.Web.Http.Metadata.Providers.DataAnnotationsModelMetadataProvider metaProvider = new System.Web.Http.Metadata.Providers.DataAnnotationsModelMetadataProvider();
var metaData = metaProvider.GetMetadataForProperty(null, typeof(Owner), "Firstname");
var validationRules = metaData.GetValidators(GlobalConfiguration.Configuration.Services.GetModelValidatorProviders());
foreach(System.Web.Http.Validation.Validators.DataAnnotationsModelValidator modelValidator in validationRules)
{
//need help here
}最后,我需要生成一个JSON定义,如下所示。
{"Firstname": "John",
"ValidationRules":[{"data-val-required":"This field is required.", "data-val-length-max":100}]}发布于 2016-03-14 07:36:29
不知道这是不是最好的方法,这就是我所做的。我已经在一个web api方法中创建了一个新的MVC上下文实例。
新变量mvcContext =
System.Web.Mvc.ControllerContext();
请参阅下面的代码。
public Dictionary<string, string> GetValidationDefinition(object container, Type type)
{
var modelMetaData = System.Web.Mvc.ModelMetadataProviders.Current.GetMetadataForProperties(container, type);
var mvcContext = new System.Web.Mvc.ControllerContext();
var validationAttributes = new Dictionary<string, string>();
foreach (var metaDataForProperty in modelMetaData)
{
var validationRulesForProperty = metaDataForProperty.GetValidators(mvcContext).SelectMany(v => v.GetClientValidationRules());
foreach (System.Web.Mvc.ModelClientValidationRule rule in validationRulesForProperty)
{
string key = metaDataForProperty.PropertyName + "-" + rule.ValidationType;
validationAttributes.Add(key, System.Web.HttpUtility.HtmlEncode(rule.ErrorMessage ?? string.Empty));
key = key + "-";
foreach (KeyValuePair<string, object> pair in rule.ValidationParameters)
{
validationAttributes.Add(key + pair.Key, System.Web.HttpUtility.HtmlAttributeEncode(pair.Value != null ? Convert.ToString(pair.Value, System.Globalization.CultureInfo.InvariantCulture) : string.Empty));
}
}
}
return validationAttributes;
}https://stackoverflow.com/questions/35930681
复制相似问题