Home > other >  Two Different Routes For One Action in ASP.Net Core 6 MVC
Two Different Routes For One Action in ASP.Net Core 6 MVC

Time:08-09

I'm trying doing same action with different routes. For example;

" ../City/AddToCity/3 "

" ../City/AddToCity?infoId=3 "

should do same action on frontend. How can i do that?

CodePudding user response:

you can use [Route] attribute.

[Route("api/[controller]")]
public class CityController{

  [Route("addtocity/{id}")]
  [Route("addtocity")]
  public IActionResult AddtoCity(int? id = null, int? infoId = null)
  {
    .....
  }
}

CodePudding user response:

Apply the following Route attribute to the action method:

[Route("/City/AddToCity/{infoId?}")]
public IActionResult AddToCity(int? infoId)
{
    .... your code
}

But if the City is your controller name, the AddToCity is the action method name and you have the following default route mapping in the Startup.cs

endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

then you don't need to apply any additional routes. Just change the parameter name to id:

public IActionResult AddToCity(int? Id)
{
    .... your code
}
  • Related