代码之家  ›  专栏  ›  技术社区  ›  Toran Billups

在aspnet mvc中添加顶级路由后,一个不相关的表单post退出工作

  •  1
  • Toran Billups  · 技术社区  · 14 年前

    最初,我正在开发的这个演示应用程序只有一个页面和一个简单的登录表单

    <form action="/Login/AuthenticateUser" method="post">
            <label for="username_or_email">Username or email</label>
            <input id="handle" name="handle" type="text" value="">
            <label for="password">Password</label>
            <input id="pass" name="pass" type="password" value="">
    </form>
    

    public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    "User",
                    "{controller}/{handle}",
                    new { Controller = "User", action = "Index", handle = UrlParameter.Optional }
                );
    
                routes.MapRoute(
                    "Default",
                    "{controller}/{action}/{id}",
                    new { controller = "Post", action = "Index", id = UrlParameter.Optional }
                );
            }
    

    这是没有问题的工作,并且有以下关联的控制器方法

    [HttpPost]
    public ActionResult AuthenticateUser(FormCollection collection)
    {
        //some code here ...
    
        return View("Index");
    }
    

    后来决定我需要一个直接查看用户信息的路径,所以我希望 http://localhost/User/handle

    所以我设计了一条路线,我可以毫无问题地看这个。但下一次尝试使用原始表单登录时(见上图),它从未在我的控制器中命中http post方法(而是http get“Index”方法)。还要注意的是-在这篇文章出现之后,浏览器中的url看起来是正确的,在本例中显示 http://localhost/Login/AuthenticateUser

    奇怪的行为无疑与新路线有关。还要注意-我没有为此auth user方法定义路由。

    我能让这些一起工作吗?另外,是什么导致了这种奇怪的行为?路线本身不对吗?

    2 回复  |  直到 14 年前
        1
  •  3
  •   Omar    14 年前

    以下路线:

    routes.MapRoute(
                    "User",
                    "{controller}/{handle}",
                    new { Controller = "User", action = "Index", handle = UrlParameter.Optional }
                );
    

    正在将您的所有请求路由到 Index 默认操作。您不允许重写 action 路由值,仅 handle /Login/AuthenticateUser 索引 行动 Login 控制器 作为 AuthenticateUser . 下面的路线永远不会被使用,因为 {controller}/{handle}

    我不知道为什么第一次就成功了,但它本不应该成功的。可能是在添加了我上面引用的路由之后,您没有构建应用程序。

    更新:

    如果你想用一些像 {controller}/{string} {控制器}/{字符串} ,但有一种方法是,如果您将常规路线设置为如下所示:

    routes.MapRoute(
             "User",
              "Page/{controller}/{action}",
              new { controller = "User", action = "Index" }
    );
    

    把这个放在 {控制器}/{字符串}

        2
  •  1
  •   dotariel    14 年前

    安装此路由调试器并使用它检查路由的外观: http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx