这是我在很多地方看到的普通代码:
[HttpPost]
public IActionResult SomeMethod([FromBody] SomeModel model)
{
if (ModelState.IsValid)
{
// doing something with model
}
else
{
// somehow notifying the user, or logging, or any other fail-strategy
}
}
这很好,直到您发现在具有一千多个服务的多个项目中,您只是为单个公司范围内的无效模型状态策略重复了许多样板代码。
如何干燥呢?我要删除所有if (ModelState.IsValid)
行:
[HttpPost]
public IActionResult SomeMethod([FromBody] SomeModel model)
{
// doing something with a valid model here,
// and knowing that some kind of middleware/action filter
// has dealt with invalid models beforehand
}
然后在此操作之前的某个中央位置具有以下代码:
public void HandleInvalidModelStates()
{
// check model state for the current action,
// and in case of being invalid, save a log to database asynchronously,
// and returning appropriate messages to inform service consumers
// about the problems.
// This strategy is exactly the same for over a thousand services.
}