控制器不应该有域逻辑。一个人应该如何忠实地遵守这一宗旨?

发布于 2024-10-12 20:37:13 字数 913 浏览 2 评论 0原文

引自《Pro ASP.NET MVC》一书第49页

当然可以放置域名 逻辑到控制器中,即使 你不应该,只是因为看起来 无论如何它都会起作用。这很容易 如果您认为自己 拥有多种 UI 技术(例如, 一个 ASP.NET MVC 应用程序加上一个 原生 iPhone 应用程序)操作 在同一底层业务域上 一层(也许有一天你会的!)。 考虑到这一点,很明显您 不想将领域逻辑放入 任何 UI 层。

为什么他在第 172 页上似乎自相矛盾?

[HttpPost]
public ActionResult CheckOut(Cart cart, ShippingDetails shippingDetails)
{
    // Empty carts can't be checked out
    if (cart.Lines.Count == 0)
        ModelState.AddModelError("Cart", "Sorry, your cart is empty!");

    if (ModelState.IsValid)
    {
        orderSubmitter.SubmitOrder(cart, shippingDetails);
        cart.Clear();
        return View("Completed");
    }
    else // Something was invalid
        return View(shippingDetails);
}

相关内容:如何避免将域逻辑放置在控制器中?

Quoting from page 49 of Pro ASP.NET MVC book

It is certainly possible to put domain
logic into a controller, even though
you shouldn’t, just because it seems
like it will work anyway. It’s easy to
avoid this if you imagine that you
have multiple UI technologies (e.g.,
an ASP.NET MVC application plus a
native iPhone application) operating
on the same underlying business domain
layer (and maybe one day you will!).
With this in mind, it’s clear that you
don’t want to put domain logic into
any of the UI layers.

Why he seems to contradict himself on page 172?

[HttpPost]
public ActionResult CheckOut(Cart cart, ShippingDetails shippingDetails)
{
    // Empty carts can't be checked out
    if (cart.Lines.Count == 0)
        ModelState.AddModelError("Cart", "Sorry, your cart is empty!");

    if (ModelState.IsValid)
    {
        orderSubmitter.SubmitOrder(cart, shippingDetails);
        cart.Clear();
        return View("Completed");
    }
    else // Something was invalid
        return View(shippingDetails);
}

Related to: How to avoid placing domain logic in controller?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

榆西 2024-10-19 20:37:13

if (cart.Lines.Count == 0) 测试确实可以由模型的验证逻辑处理,不应放置在控制器中。就我个人而言,我会像这样重写这个控制器操作:

[HttpPost]
public ActionResult CheckOut(CheckOutViewModel checkOut)
{
    if (ModelState.IsValid)
    {
        orderSubmitter.SubmitOrder(checkOut);
        return View("Completed");
    }
    return View(checkOut);
}

The if (cart.Lines.Count == 0) test could indeed have been handled by the validation logic of the model and shouldn't be placed in the controller. Personally I would rewrite this controller action like so:

[HttpPost]
public ActionResult CheckOut(CheckOutViewModel checkOut)
{
    if (ModelState.IsValid)
    {
        orderSubmitter.SubmitOrder(checkOut);
        return View("Completed");
    }
    return View(checkOut);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文