Search code examples
asp.net-mvcasp.net-mvc-5asp.net-mvc-routingattributerouting

MVC 5 Route not found if parameter is passed in URL


I have following methods in my MVC controller:

[HttpGet]
public ActionResult Add(Guid b)
{
    ViewBag.Title="Add Location";
    //init some info
    return View("Edit",<Model>);
}

[HttpGet]
public ActionResult Edit(Guid l)
{
    ViewBag.Title="Edit Location";
    //get object from db
    return View("Edit",<Model>);
}

Following is the route registration:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Now when I try to access following two routes:

1. http://localhost:60732/Location/Add?b=512f770f-51c3-4791-8eba-61fe753e2a83
2. http://localhost:60732/Location/Edit?l=512f770f-51c3-4791-8eba-61fe753e2a83

First one works but 2nd gives 404.

I have also tried AttributeRouting with following routes:

[HttpGet]
[Route("Location/AddLocation/{g}")]
public ActionResult Add(Guid g)

[HttpGet]
[Route("Location/EditLocation/{l}")]
public ActionResult Edit(Guid l)

Again,

 http://localhost:60732/Location/AddLocation/512f770f-51c3-4791-8eba-61fe753e2a83

works but

 http://localhost:60732/Location/EditLocation/512f770f-51c3-4791-8eba-61fe753e2a83

does not.

What am I doing wrong?

Strangely, if I pass wrong Guid like:

 http://localhost:60732/Location/EditLocation/512f770f

It gives following error:

The parameters dictionary contains a null entry for parameter 'l' of non-nullable type
'System.Guid' for method 'System.Web.Mvc.ActionResult Edit(System.Guid)' in
'AppointmentScheduler.Controllers.LocationController'. An optional parameter must be a
reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

Solution

  • There is nothing wrong with your routing here. However, the code in your Edit method must itself be throwing a 404 error by throwing HttpNotFound.