How to use an Area in ASP.NET Core

前端 未结 8 762
[愿得一人]
[愿得一人] 2020-11-28 23:45

How do I use an Area in ASP.NET Core?

I have an app that needs an Admin section. This section requires its Views to be placed in that area. All request

8条回答
  •  天命终不由人
    2020-11-29 00:19

    Areas Implementation in Routing First Create Area(Admin) using VS and add the following code into Startup.cs First Way to Implement:- Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing. Startup.cs

     app.UseMvc(routes =>
                {
                    routes.MapRoute(
                      name: "areas",
                      template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
                    );
                });
    

    Note: Area routing must be placed first with non area routing, area: exists is compulsory to add area routing.

    Controller Code:

    [Area("Admin")] 
        public class LoginController : Controller
        {
            public IActionResult Index()
            {
                return Content("Area Admin Login Controller and Index Action");
            }
        }
    

    This route may be called using http://localhost:111/Admin

    Second Way to Implement Area Routing:- Add Following code into startup.cs.

    app.UseMvc(routes =>
                {
                    routes.MapAreaRoute(
        name: "default",
        areaName: "Guest",
        template: "Guest/{controller}/{action}/{id?}",
        defaults: new { controller = "GuestLogin", action = "Index" });
                });
    

    Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into the newly created controller.

    [Area("Guest")]
        public class GuestLoginController : Controller
        {
            public IActionResult Index()
            {
                return Content("Area Guest Login Controller and Index Action");
            }
        }
    

    This route may be called using http://localhost:111/Guest

提交回复
热议问题