0

您能否提供一个代码示例,其中包含用于创建服务层类(应该由 Web 前端、Web API 等使用)的基本架构指南?

你认为这是一个很好的教程吗?http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs

4

1 回答 1

4

我个人不喜欢那篇文章如何描述将错误从服务层传递回控制器(使用 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 提到的,让服务抛出验证异常,在全局过滤器中捕获它们并插入模型状态。

于 2012-06-19T18:32:23.353 回答