MVC 5路由属性 [英] MVC 5 Routing Attribute

查看:70
本文介绍了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
);

现在,我像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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆