【发布时间】:2016-03-03 20:22:17
【问题描述】:
我有一个基本的 C# Web Api 2 控制器,它有一个 POST 方法来创建实体
public HttpResponseMessage Post(UserModel userModel){ ... }
还有一个 PUT 方法来更新所述模型
public HttpResponseMessage Put(int id, UserModel userModel) { ... }
这里是用户模型
public class UserModel
{
public virtual Name { get; set; }
public virtual Username { get; set; }
}
对于我的验证器,我想验证该名称未在 Post 上使用 - 很简单。对于 PUT,我需要验证该名称是否未被其他用户使用,但当然该特定用户将具有相同的用户名。
public class UserModelValidator : AbstractValidator<UserModel>
{
public UserModelValidator()
{
RuleFor(user => user.Username)
.Must(NotDuplicateName).WithMessage("The username is taken");
}
private bool NotDuplicateName(string username)
{
var isValid = false;
//Access repository and check to see if username is not in use
//If it is in use by this user, then it is ok - but user ID is
//in the route parameter and not in the model. How do I access?
return isValid;
}
}
我正在使用 AutoFac,所以也许有一种方法可以将 HttpRequest 注入验证器并以这种方式获取路由数据。
或者我可以创建一个模型绑定器来查找路线数据并将其添加到模型中?
或者有什么简单的方法吗?
【问题讨论】:
标签: c# asp.net-web-api fluentvalidation