我在用着自动模型验证 https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/(参见“更好的输入处理”)保持我的控制器干净;所以:
[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);
}
becomes:
[HttpPost]
[ProducesResponseType(201)]
public ActionResult<Product> Post(Product product)
{
_repository.AddProduct(product);
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
但是,我确实有一些具有电话号码属性的模型。我想将这些“正常化”before调用模型验证。我的意思是我想标准化这些属性(类型string
)来自各种输入,例如:
- +31 23 456 7890
- (023)4567890
- 023 - 4567 890
- ...
To E.164 表示法 https://en.wikipedia.org/wiki/E.164:
因此,无论用户以何种形式输入电话号码,在调用验证之前,我都想确保它始终采用 E.164 形式(“标准化”)。如何进行这种标准化是无关紧要的(我使用库电话号码 https://github.com/googlei18n/libphonenumber如果你坚持)。作为第二个,也许不那么复杂的例子,我可以想象一个字符串在调用验证之前总是大写/小写。
调用我的标准化过程的正确或最佳方法是什么before验证被调用?我需要写一些中间件吗?
同样相关的是:我的模型包含属性,因此规范化器知道要规范化哪些属性(以及如何规范化):
class ExampleModel {
public int Id { get; set; }
public string Name { get; set; }
[NormalizedNumber(NumberFormat.E164)]
public string Phonenumber { get; set; }
}
I guess the middleware(? or whatever the solution is going to be) can then take a model, figure out if any of the properties (recursively) have the attribute and invoke the normalizer if needed.