gpt4 book ai didi

asp.net-mvc - ASP.NET MVC View 或 URL 的深度应该是多少?

转载 作者:行者123 更新时间:2023-12-04 10:32:38 25 4
gpt4 key购买 nike

我还在学习 ASP.NET MVC。使用 webforms,我会创建一个新文件夹,我们称之为 admin。在那里我可能有很多关于 create_product、edit_product 等的页面。所以 URL 可能看起来像 http://somesite.com/admin/create_product.aspx .

但是对于 MVC,它有点不同。我想看看什么是最好的方法来做到这一点。

会做http://somesite.com/admin/product/create对吗?或者应该只是http://somesite.com/product/create ?如果我采用第一种方式,我是将所有内容都放在“管理员” Controller 中还是应该将其分离到“产品” Controller 中?

我知道这可能是主观的或个人的选择,但我想得到一些建议。

谢谢。

最佳答案

ASP.NET MVC(更一般地说,.NET 3.5 SP1 中所有 ASP.NET 通用的 URL 路由引擎)的部分好处是可以灵活配置 URL 以映射到您喜欢的任何文件夹/文件结构。这意味着在开始构建项目后修改 URL 比使用 WebForms 时代要容易得多。

对于您的具体问题:

  • 一个管理 Controller 与产品 Controller - 一般而言,指导方针是让 Controller 保持专注,以便于测试和维护。出于这个原因,我建议在您的 CRUD 操作中为每个对象类型(如产品)使用一个 Controller 。您的情况示例:

    /管理员/产品/创建

    /admin/product/edit/34 或/admin/product/edit/red-shoes(如果名称是唯一的)

    在任一情况下,Create、Edit、Details 操作都将在 ProductController 中。您可能只有“管理操作”(如创建和编辑)的自定义路由来限制它们的使用(并将“管理”文本添加到 URL),然后详细信息操作将可供您网站的所有访问者使用。
  • 保护管理员 View - MVC 要记住的一个重要事实:所有请求都直接发送到 Controller ,而不是 View 。这意味着旧的“使用 web.config 保护目录”(通常)不适用于 MVC 来保护您的管理员。相反,您现在应该将安全性直接应用于 Controller 。这可以通过使用 Controller 类的属性轻松实现,例如:
  • [授权] - 只需检查用户是否已登录
  • [Authorize(Roles = "Admin")] - 限制为特定的用户角色
  • [Authorize(Users = "Joe")] - 仅限特定用户

  • 您甚至可以为站点中的“管理员” View 创建自定义路由,并通过在 URL 路由中强制执行授权检查来限制对这些 View 的访问,如下所示:
    routes.MapRoute(
    "Admin",
    "Admin/{controller}/{action}",
    new { controller = "Product", action = "Index" },
    new { authenticated= new AuthenticatedConstraint()}
    );

    其中 AuthenticatedConstraint 看起来像:
    using System.Web;
    using System.Web.Routing;
    public class AuthenticatedConstraint : IRouteConstraint
    {
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
    return httpContext.Request.IsAuthenticated;
    }
    }

    Stephen Walther 博客的详细信息:
    ASP.NET MVC Tip #30 – Create Custom Route Constraints

    关于asp.net-mvc - ASP.NET MVC View 或 URL 的深度应该是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1412090/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com