How to use Optional URI Parameters ? | ASP.Net MVC Interview Question

, ,

  • To that you can add aquestion mark to the Route parameter
  • Well, It's like this : [Route("Pet/{petKey?}")]

    PetController.cs

  public class PetController : Controller
    {
        // eg: /Pet
        // eg: /Pet/123
        [Route("Pet/{petKey?}")]
        public ActionResult GetPet(string petKey)
        {
            return View();
        }
       }

Key point of the above code

  • In the above example, both/Pet and /Pet/123 will Route to the “GetPet” Action

Above Route on Browser is as below