【问题标题】:ASP.NET MVC Routing - "Blank" RouteASP.NET MVC 路由 - “空白”路由
【发布时间】:2023-04-03 04:16:02
【问题描述】:

我可以像这样设置一个从根级 URL 映射的路由吗?

http://localhost:49658/

我使用的是 VS2010 内置的网络服务器。

尝试使用空白或单斜杠 URL 字符串设置路由不起作用:

routes.MapRoute(
    "Default",
    "/",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

它会导致错误“路由 URL 不能以 '/' 或 '~' 字符开头并且不能包含 '?'特点。”。提前致谢!我的整个路线定义在这里:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "EditingTitles", // Route name
            "{controller}/{action}/{startingLetter}", // URL with parameters
            new { controller = "Admin", action = "Index", startingLetter = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

【问题讨论】:

  • 向我们展示您的其他路线,我遇到了与上述类似的问题(以及您对 XSaint32 答案的注释),除非我指定了控制器/操作,否则我的默认路线导致 404,这是由于在我的路线中某处命名错误的路线

标签: asp.net-mvc routing


【解决方案1】:

你想在这里实现什么...一个看起来像这样的 URL? http://www.acme.com/ ?因为如果你是,默认路由将在没有指定任何参数时实现。

// Default Route:
routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Home", action = "Index", id = String.Empty } // Parameter defaults
);

【讨论】:

  • 你说得对,那个 URL 就是我想要实现的。我已经有一条与您指定的路线完全相同的路线。 . .但是当我对我的项目进行 F5 并点击默认 URL 时,我收到了 HTTP 404(“找不到资源”)错误,所以我似乎必须以某种方式专门处理“空 URL”的情况。
  • 你能把那条路线贴在这里吗?
  • 听起来像另一个指定的路由不好,我遇到了类似的问题,我的默认路由被覆盖并且不处理根 URL。请在问题中发布您的所有路线。
  • 我推荐使用 Phil Haack 的路由调试器:haacked.com/archive/2008/03/13/url-routing-debugger.aspx
  • 好点;我更新了问题以包括我的所有路线。我将检查发布的路由调试器。谢谢!
【解决方案2】:

使用 ASPNET MVC5: RouteConfig.cs 文件:

 public static void RegisterRoutes(RouteCollection routes)
 {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Homepage",
        url: "",
        defaults: new { controller = "Content", action = "Index" }
    );
    routes.MapRoute(
        name: "foo",
        url: "bar",
        defaults: new { controller = "Content", action = "Index" }
    );
    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{title}",
        defaults: new { controller = "Content", action = "Details", title = UrlParameter.Optional }
    );
}

加:
如果您希望将您的主页自动重定向到另一个路由,例如“http://www.yoursite.com/”到“http://www.yoursite.com/bar”,只需使用方法RedirectToRoute()

public class ContentController : Controller
    {
        public ActionResult Index()
        {
            return RedirectToRoute("foo");
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多