2016-03-11 60 views
1

我有一個域對象所有者。這有一些數據註釋將用於Web api post方法進行驗證。Web Api 2序列化數據註釋

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; } 

} 

現在我需要將此對象的驗證規則(在數據註釋中定義)發送到獲取請求的前端。我在尋找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}]} 

回答

0

不知道這是否是最好的方法,這是我所做的。我在web api方法中創建了一個新的MVC上下文實例。

var mvcContext = new 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; 
    }