ASP.NET MVC 视图或 URL 应该有多深?

2024-02-02

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

但对于 MVC 来说,情况有些不同。我正在尝试看看什么是最好的方法来做到这一点。

会做http://somesite.com/admin/product/create http://somesite.com/admin/product/create对吗?或者应该只是http://somesite.com/product/create http://somesite.com/product/create?如果我按照第一种方式进行操作,我是否将所有内容都放入“管理”控制器中,还是应该将其分离到“产品”控制器中?

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

Thanks.


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

对于您的具体问题:

  • 一个管理控制器与一个产品控制器- 一般来说,指导是让控制器保持专注,以便它们更容易测试和维护。出于这个原因,我建议对每个对象类型(例如产品)使用一个控制器来执行 CRUD 操作。您的案例示例:

    /管理/产品/创建

    /admin/product/edit/34 或 /admin/product/edit/red-shoes (if名字是唯一的)

    无论哪种情况,“创建”、“编辑”、“详细信息”操作都将位于 ProductController 中。您可能只是为“管理操作”(如创建和编辑)设置了自定义路由,以限制其使用(并将“管理”文本添加到 URL),然后您网站的所有访问者都可以使用“详细信息”操作。

  • Securing Admin Views - One important fact to remember with MVC: all requests go directly to controllers, not views. That means the old "secure a directory with web.config" does not apply (usually) to MVC for securing your Admin. Instead, you should now apply security directly to the controllers. This can easily be achieved by using attributes to Controller classes like:
    • [授权] - 仅检查用户是否已登录
    • [Authorize(Roles = "Admin")] - 限制特定用户角色
    • [Authorize(Users = "Joe")] - 仅限特定用户

您甚至可以为站点中的“管理”视图创建自定义路由,并通过在 URL 路由中强制执行授权检查来限制对这些视图的访问,如下所示:

routes.MapRoute(
  "Admin",
  "Admin/{controller}/{action}",
  new { controller = "Product", action = "Index" },
  new { authenticated= new 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 技巧 #30 – 创建自定义路由约束 http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC 视图或 URL 应该有多深? 的相关文章

随机推荐