MVC 5路由属性

编程入门 行业动态 更新时间:2024-10-26 16:32:04
本文介绍了MVC 5路由属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有家庭控制器,我的动作名称是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 );

现在,我像localhost:11045/Home/Index这样称呼我的页面是正确的.

Now I call my page like 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(); }

推荐答案

对于 ASP.NET MVC 5中的属性路由

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路由属性

本文发布于:2023-11-12 13:45:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   属性   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!