ASP.NET MVC How many levels deep should a view or URL be?

前端 未结 3 1801
轻奢々
轻奢々 2021-02-09 09:46

I am still learning ASP.NET MVC. With webforms, I would create a new folder let\'s call it admin. In there I might have many pages for create_product, edit_product, etc. So t

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-09 10:21

    Part of the benefit of ASP.NET MVC (and more generally, the URL Routing Engine common to all of ASP.NET in .NET 3.5 SP1) is that the URLs can be flexibly configured to map to any folder / file structure you prefer. That means it's much easier than it was in the days of WebForms to modify your URLs after you've started building your project.

    To your specific questions:

    • One Admin Controller vs. Product Controller - In general, the guidance is to keep controllers focused so that they are easier to test and maintain. For that reason, I would suggest using a single controller per object type (like Product) with your CRUD actions. Examples in your case:

      /admin/product/create

      /admin/product/edit/34 or /admin/product/edit/red-shoes (if name is unique)

      In either case, the Create, Edit, Deatils actions will all be in the ProductController. You may just have custom routes for the "admin actions" (like Create and Edit) that limit their usage (and add the "admin" text to the URL), and then the Details action would be usable by all visitors to your site.

    • 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] - Just checks that the user is logged-in
      • [Authorize(Roles = "Admin")] - Limit to specific user roles
      • [Authorize(Users = "Joe")] - Limit to specific users

    You can even create a custom route for "Admin" views in your site and limit access to those views by enforcing your authorization check in the URL routing, like this:

    routes.MapRoute(
      "Admin",
      "Admin/{controller}/{action}",
      new { controller = "Product", action = "Index" },
      new { authenticated= new AuthenticatedConstraint()}
    );
    

    Where AuthenticatedConstraint looks something like:

    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;
      }
    }
    

    Good details on Stephen Walther's blog: ASP.NET MVC Tip #30 – Create Custom Route Constraints

提交回复
热议问题