How to use an Area in ASP.NET Core

前端 未结 8 714
[愿得一人]
[愿得一人] 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

    0 讨论(0)
  • 2020-11-29 00:19
    With .net core, following is needed to be added in the startup file if you are adding an area:
    
         app.UseMvc(routes =>
                {
                    routes.MapRoute(
                      name: "areas",
                      template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                    );
                });
    
    After that you can just simply mark your area and route in the controller, i.e
         [Area("Order")]
         [Route("order")]
    

    it works for me.

    0 讨论(0)
提交回复
热议问题