如果在URL中传递参数,则找不到MVC 5 Route

时间:2014-12-29 02:04:41

标签: asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing attributerouting

我的MVC控制器中有以下方法:

[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>);
}

以下是路线注册:

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

现在,当我尝试访问以下两条路线时:

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

第一个有效但第二个有404个。

我还尝试了AttributeRouting以下路线:

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

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

再次,

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

有效但

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

没有。

我做错了什么?

奇怪的是,如果我传递了错误的Guid

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

它出现以下错误:

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

2 个答案:

答案 0 :(得分:2)

此处的路由没有任何问题。但是,Edit方法中的代码本身必须通过抛出HttpNotFound来抛出404错误。

答案 1 :(得分:1)

我只希望这是2014年的最后一次WTF。我传递id(Guid)并尝试从db获取对象。实际上,它无法找到它并且我正在返回:HttpNotFound(我想从某种API方法复制)。所以我总是为这条路线获得404