您能否提供一个代码示例,其中包含创建服务层类(应该由 Web 前端、Web API 等使用)的基本架构指南?
你认为这是一个很好的教程吗? http://www.asp.net/mvc/tutorials/older 版本/模型-(数据)/使用服务层-cs 进行验证
我个人不喜欢这篇文章描述将错误从服务层传递回控制器的方式(使用 IValidationDictionary),我会让它更像这样工作:
[Authorize]
public class AccountController : Controller
{
private readonly IMembershipService membershipService;
// service initialization is handled by IoC container
public AccountController(IMembershipService membershipService)
{
this.membershipService = membershipService;
}
// .. some other stuff ..
[AllowAnonymous, HttpPost]
public ActionResult Register(RegisterModel model)
{
if (this.ModelSteate.IsValid)
{
var result = this.membershipService.CreateUser(
model.UserName, model.Password, model.Email, isApproved: true
);
if (result.Success)
{
FormsAuthentication.SetAuthCookie(
model.UserName, createPersistentCookie: false
);
return this.RedirectToAction("Index", "Home");
}
result.Errors.CopyTo(this.ModelState);
}
return this.View();
}
}
或者.. 正如 mikalai 提到的,让服务抛出验证异常,在全局过滤器中捕获它们并插入到模型状态中。