MVC 5路由属性 [英] MVC 5 Routing Attribute
问题描述
我有家庭控制器,我的动作名称是Index.在我的路线"配置中,如下所示的路线.
I have the Home Controller and my Action name is Index. In My route config the routes like below.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
现在,我像http://localhost:11045/Home/Index
这样称呼我的页面是正确的.
Now I call my page like http://localhost:11045/Home/Index
is correct.
如果我按照以下方式调用页面,则该页面应重定向到错误页面.
localhost:11045/Home/Index/98
或
localhost:11045/Home/Index/?id=98
.
If I call my page like following it should redirect to error page.
localhost:11045/Home/Index/98
or
localhost:11045/Home/Index/?id=98
.
如何使用路由属性处理此问题.
How to handle this using routing attribute.
我在Controller中的操作如下所示.
My Action in Controller look like below.
public ActionResult Index()
{
return View();
}
推荐答案
For Attribute Routing in ASP.NET MVC 5
像这样装饰您的控制器
[RoutePrefix("Home")]
public HomeController : Controller {
//GET Home/Index
[HttpGet]
[Route("Index")]
public ActionResult Index() {
return View();
}
}
像这样在路由表中启用它
And enable it in route table like this
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 = "" }
);
}
}
这篇关于MVC 5路由属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!