纠正我在 mvc 中的 url 路由

correct me on url routing in mvc

在我的 globas.asax 文件中,我有一个注册路径

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

在我的操作中 "BigClientLogin" 它重定向到一个名为 "NewLogin" 的新操作。所以目前我当前的 url 看起来像“http://localhost:65423/Authentication/NewLogin”。但是我需要我的 url “http://localhost:65423/Login”格式。将动作名称从 "NewLogin" 更改为 "Login" 是不可能的,因为我在我的解决方案中的很多地方都调用了这个动作。那么在 mvc 路由中是否有任何替代解决方案?或者这是不可能的,最好是更改我的操作名称?

一个简单的解决方案是使用 ActionName 属性。把这个放在你的操作方法上

[ActionName("Login")]
public ActionResult NewLogin(...)
{
    ...
}

这只会更改操作名称,如果您只希望路径为 /login,请使用 Route 属性:

[Route("login", Name = "Login")]
public ActionResult NewLogin(...)

您可以尝试将动作别名定义为属性,详情请参阅文章: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx/

[ActionName("View")]
public ActionResult ViewSomething(string id) {  
    return View();
}

The ActionNameAttribute redefines the name of this action to be “View”. Thus this method is invoked in response to requests for /home/view, but not for /home/viewsomething.

简单 - 将其放在上面的默认路由之前:

routes.MapRoute(
            "BigClientLogin", // Route name
            "Login", // URL with parameters
            new { controller = "Authentication", action = "BigClientLogin" } // Parameter defaults
        );

几个选项:

首先,为这个新的登录操作映射一个路由:

routes.MapRoute(
  "NewLogin",
  "Login",
  new { controller = "Authentication", action = "NewLogin" }
);

另一个选项(如果启用)是利用属性路由:

public class AuthenticationController : Controller
{
    [Route("~/Login", Name = "NewLogin")]
    public ActionResult NewLogin(...)
    {
        /* ... */
    }
}

(只要确保在 RouteConfig.cs 中调用了 routes.MapMvcAttributeRoutes()

使用其中任何一个,您将拥有一个可以在您的解决方案中引用的命名路由(这将允许您在将来根据需要更改它):

@Html.RouteLink("Login", "NewLogin")