[英]Model normalization before model validation in Asp.Net Core 2.0+
我正在使用自動模型驗證 (請參閱“更好的輸入處理”)來保持控制器清潔; 所以:
[HttpPost]
[ProducesResponseType(typeof(Product), 201)]
public IActionResult Post([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
product = _repository.AddProduct(product);
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
變為:
[HttpPost]
[ProducesResponseType(201)]
public ActionResult<Product> Post(Product product)
{
_repository.AddProduct(product);
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
但是,我確實有一些具有phonenumber屬性的模型。 我想在調用模型驗證之前對它們進行“規范化”。 我的意思是我想從各種輸入中規范這些屬性( string
類型):
對於E.164表示法 :
因此,無論用戶以什么形式輸入電話號碼,在調用驗證之前,我要確保它始終為E.164形式(“規范化”)。 標准化的完成方式無關緊要(如果您堅持要使用libphonenumber )。 作為第二個,也許不太復雜的例子,我可以想象一個字符串在調用驗證之前總是大寫/小寫。
在調用驗證之前調用我的規范化過程的正確或最佳方法是什么? 我需要編寫一些中間件嗎?
也相關:我的模型包含屬性,因此規范化器知道要規范化哪些屬性(以及如何規范化):
class ExampleModel {
public int Id { get; set; }
public string Name { get; set; }
[NormalizedNumber(NumberFormat.E164)]
public string Phonenumber { get; set; }
}
我猜中間件(或解決方案將要采用的解決方案)可以采用一個模型,找出(遞歸)任何屬性是否具有該屬性,並在需要時調用規范化器。
也許您可以使用Formatter使用類似的方法。 我已經使用類似的方法將API中的所有傳入日期轉換為UTC格式
public class JsonModelFormatter : JsonMediaTypeFormatter
{
public override System.Threading.Tasks.Task<Object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
{
System.Threading.Tasks.Task<Object> baseTask = base.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);
if (baseTask.Result != null)
{
var properties = baseTask.Result.GetType().GetProperties();
foreach (var property in properties)
{
//Check Property attribute and decide if you need to format it
if (property.CustomAttributes.Where (x=> you condition here))
{
if (property.CanWrite && property.GetValue(baseTask.Result, null) != null)
{
var propValue = ((string)property.GetValue(baseTask.Result, null));
//Update propValue here
property.SetValue(baseTask.Result, newPropValue);
}
}
}
}
return baseTask;
}
public override bool CanReadType(Type type)
{
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.