0

通过我在我的MVC控制器下面的方法未找到:MVC 5途径,如果参数在URL

[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 

第一个作品,但第2给出了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 
+0

我看到这段代码没有错,它应该工作。我们在这里错过了什么吗? – DavidG

+0

@DavidG这是我无法弄清楚的。这里没有什么特别的东西,但它仍然不起作用。 – TheVillageIdiot

+1

通过编辑,看起来错误来源于操作方法。这是否会抛出404错误或'HttpNotFound'异常? – DavidG

回答

2

这里的路由没有任何问题。但是,您的Edit方法中的代码本身必须抛出HttpNotFound以引发404错误。

1

我只是希望这是2014年我通过ID(GUID)去年WTF和尝试从数据库中获取对象。其实,它不能找到它,我回来了:HttpNotFound(我想从一些API方法复制)。所以我总是得到404这条路线。