use*_*320 10 c# asp.net asp.net-mvc asp.net-mvc-routing
我有家庭控制器,我的动作名称是索引.在我的路线中配置如下的路线.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)
现在我称我的页面http://localhost:11045/Home/Index
是正确的.
如果我像下面一样调用我的页面,它应该重定向到错误页面.
localhost:11045/Home/Index/98
或
localhost:11045/Home/Index/?id=98
.
如何使用路由属性处理此问题.
我在Controller中的行为如下所示.
public ActionResult Index()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
Nko*_*osi 26
像这样装饰你的控制器
[RoutePrefix("Home")]
public HomeController : Controller {
//GET Home/Index
[HttpGet]
[Route("Index")]
public ActionResult Index() {
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
并在路由表中启用它
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enable attribute routing
routes.MapMvcAttributeRoutes();
//convention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = "" }
);
}
}
Run Code Online (Sandbox Code Playgroud)
请在此处查看有关路由的信息:http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs
最有可能的是,默认路由应该如下所示:
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)
另外,看起来索引操作方法缺少一个参数,如下所示:
public ActionResult Index(string id)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
尝试放入string id
您的 Index 方法。
归档时间: |
|
查看次数: |
22454 次 |
最近记录: |