为什么这条路线不能正常工作?

han*_*sjw 2 c# model-view-controller asp.net-mvc

我真的很生气.

这是我的Global.asax中的内容

routes.MapRoute("BlogDetails", "Blogs/{id}/{title}", new { controller = "Blogs", action = "Details", id = "" });
routes.MapRoute(
"Default",                                              // Route name
"{controller}/{action}/{id}",                           // URL with parameters
new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)

这是我唯一的两条路线.

当我尝试访问时

http:// mysite/Blogs/Edit/1它不起作用我收到此错误

参数字典包含'mysite.Controllers.BlogsController'中方法'System.Web.Mvc.ActionResult Details(Int32)'的非可空类型'System.Int32'的参数'id'的空条目.可选参数必须是引用类型,可空类型,或者声明为可选参数.

为什么会这种情况继续发生?

谢谢

我还应该添加我的控制器代码

//
// GET: /Blogs/Edit/5

[Authorize]
public ActionResult Edit(int id)
{
  // do a bunch of stuff and return something
}
Run Code Online (Sandbox Code Playgroud)

Oma*_*mar 5

请尝试以下方法

routes.MapRoute("BlogDetails", "Blogs/{id}/{title}",
 new { controller = "Blogs", action = "Details"},
 new { id = @"\d+" });
Run Code Online (Sandbox Code Playgroud)

就MVC路由而言,{id}可以是任何东西(甚至字符串),因此它匹配Edit为字符串,不能进入id您的操作的int .

添加new { id= @"\d+" }作为额外参数告诉路由系统仅匹配数字.

http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/mvc/tutorial-24-cs.aspx