ASP.NET MVC应用程序最佳实践中的服务层类

时间:2012-06-19 13:59:36

标签: c# asp.net-mvc architecture asp.net-mvc-4

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

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

1 个答案:

答案 0 :(得分: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所提到的,使服务抛出验证异常,在全局过滤器中捕获它们并插入模型状态。