Search code examples
routesasp.net-core-mvc.net-7.0asp.net-core-7.0

In an ASP.NET Core 7 MVC web application, how do you start a debugging session at a specific path based on an area?


In my ASP.NET Core 7 MVC web application, I am debugging using IIS Express. When the application starts, I want the first route to load to be:

https://localhost:44341/fantasy-football/create/cheatsheet/edit/1645168

This makes it faster to debug as I don't have to start at the home page, then click through various pages to get to the route I'm testing.

This URL route maps to a controller housed in an area:

/Areas/FantasyFootball/Controllers/Create/CheatSheetController.cs 

And the action method signature is this:

[Route("/fantasy-football/create/cheatsheet/edit/{id?}", Name = "fantasyfootball.create.cheatsheet.edit")]
public IActionResult Edit(int id)

I have tried to update the application url in the launchSettings.json file, but it still loads the default route defined in Program.cs.

"iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
        "applicationUrl": "http://localhost:51696/fantasy-football/create/cheatsheet/edit/1645168",
        "sslPort": 44341
    }
},

I tried updating the default route in Program.cs:

app.MapControllerRoute(
    name: "default",
    pattern: "{area=FantasyFootball}/{controller=CheatSheet}/{action=Edit}/{id=1645168}");

And this seems to load the correct URL in the browser, but I get a 404 error.


Solution

  • Please try as below:

    //Area attribute is important
    [Area("fantasy-football")]
        public class CheatSheetController : Controller
        {
            //Remove the [Route] Atrribute which would which would override the route parttern you registed in Program.cs
            public IActionResult Edit(int id)
            {
                return Ok();
            }               
            
        }
    

    in Program.cs:

        app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    app.MapAreaControllerRoute(
        "fantasy",
        "fantasy-football",
        pattern: "{area}/Create/{controller}/{action}/{id?}"
        );
    

    Keep

    "applicationUrl": "http://localhost:51696
    

    in your launchsetting.json

    add

    "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "fantasy-football/create/cheatsheet/edit/1645168",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
    

    in profile section

    or right click on your project=>properties=>debug=>open debug launch profiles UI

    enter image description here

    It's ok now,when I debug:

    enter image description here