HTML.ActionLink使用控制器和操作作为查询参数生成URL

时间:2018-09-17 20:49:28

标签: asp.net

使用Asp.net 5.2.6,我向AuthController添加了一个新的Register Action,并尝试在Login页面上生成一个ActionLink。无论我做什么,URL都会显​​示为

http://host/?action=Register&controller=Auth

但是我期待

http://host/Auth/Register

我尝试了属性路由,并在RouteConfig.cs中添加了特定的映射

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

    // Web Forms default
    routes.MapPageRoute(
        "WebFormDefault",
        "",
        "~/Default.aspx"
    );

    routes.MapMvcAttributeRoutes();

    AreaRegistration.RegisterAllAreas();

    // Tried with and without this
    routes.MapRoute(
        "Registration",
        "Auth/Register",
        new { controller = "Auth", action = "Register" });

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

我在AuthController中的新操作方法如下。 AuthController的其余部分只是“获取和发布”登录操作​​。

[HttpGet]
public ActionResult Register()
{

    return View("Register", new Register());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Register register)
{

    // validation here
    ...
    return View("Register", register);

}

这是构建链接的方式,我也尝试过使用相同的较短方法签名。

@Html.ActionLink("Register Now", "Register", "Auth", null, new { @class = "btn btn-default" })

我对此完全感到困惑,过去我从未遇到过这种麻烦。请帮忙!

1 个答案:

答案 0 :(得分:0)

Its because of this code your have :

// Tried with and without this
routes.MapRoute(
    "Registration",
    "Auth/Register",
    new { controller = "Auth", action = "Register" });

Either remove this, or put it at the very end - after the MVC Default.