简体   繁体   中英

How to define route for multiple areas in .net core

Initially I had only one area and I wanted that as the default route so I configured it like:

routes.MapRoute(
    name: "default",
    template: "{area=Product}/{controller=Home}/{action=Index}/{id?}");

and it was working fine. Now I want to include another area "Order" and configured the route like:

 app.UseMvc(routes =>
 {
     routes.MapRoute(
            name: "default",
            template: "{area=Product}/{controller=Home}/{action=Index}/{id?}");
     routes.MapRoute(
            name: "orderRoute",
            template: "{area=Order}/{controller=Home}/{action=Index}/{id?}");
 });

and in Home controller of Order area:

[Area("Order")]
public class HomeController : Controller
{

Now when I hit https://localhost:44632/order I am getting 404 not found but https://localhost:44632/product is working fine. I also tried to configure orderRoute before default route but still got same results. What am I doing wrong?

It looks correct. Just needs a change. You need to add default route in the end not as the first route. just interchange and it should work.


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")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM