RouteAttribute破坏了我的默认路由 [英] RouteAttribute broke my Default route

查看:294
本文介绍了RouteAttribute破坏了我的默认路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将 [Route(Name ="WhatEver")] 应用于操作(用作默认站点路由),则在访问站点根目录时会收到HTTP 404.

If I apply [Route(Name = "WhatEver")] to action, which I use as Default site route, I get HTTP 404 when accesing site root.

例如:

  • 创建新的示例MVC项目.
  • 添加属性路由:

  • Create new sample MVC project.
  • Add attributes routing:

// file: App_Start/RouteConfig.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes(); // Add this line
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

  • 添加路由属性

  • Add routing attributes

    [RoutePrefix("Zome")]
    public class HomeController : Controller
    {
        [Route(Name = "Zndex")]
        public ActionResult Index()
        {
            return View();
        }
        ...
    }
    

  • 现在,当您启动项目进行调试时,将出现HTTP错误404.我该如何在默认路由映射中使用属性路由?

    And now, when you start your project for debuging, you will have HTTP Error 404. How should I use attribute routing with default route mapping?

    推荐答案

    对于使用带有路由前缀的属性路由的默认路由,您需要将路由模板设置为空字符串.如果控制器已经具有路由前缀,也可以使用~/覆盖站点根.

    For default route using attribute routing with route prefix you need to set the route template as an empty string. You can also override the site root using ~/ if the controller already has a route prefix.

    [RoutePrefix("Zome")]
    public class HomeController : Controller {
        [HttpGet]
        [Route("", Name = "Zndex")]      //Matches GET /Zome
        [Route("Zndex")]                 //Matches GET /Zome/Zndex
        [Route("~/", Name = "default")]  //Matches GET /  <-- site root
        public ActionResult Index() {
            return View();
        }
        //...
    }
    

    也就是说,在控制器上使用属性路由时,它不再与基于约定的路由匹配.控制器要么全部基于属性,要么全部基于约定,不要混用.

    That said, when using attribute routing on a controller it no longer matches convention-based routes. The controller is either all attribute-based or all convention-based that do not mix.

    参考 ASP.NET MVC 5中的属性路由

    这篇关于RouteAttribute破坏了我的默认路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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