C# 更正我在mvc中的url路由
在globas.asax文件中,我有一个注册路径C# 更正我在mvc中的url路由,c#,asp.net-mvc,asp.net-mvc-routing,global-asax,C#,Asp.net Mvc,Asp.net Mvc Routing,Global Asax,在globas.asax文件中,我有一个注册路径 routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Authentication", action = "BigClientLogin", id = UrlParameter.Optional
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Authentication", action = "BigClientLogin", id = UrlParameter.Optional } // Parameter defaults
);
在我的操作“BigClientLogin”中,它重定向到一个名为“NewLogin”的新操作。所以目前我的当前url看起来像“”。但我需要我的url
“”格式。无法将操作名称从“NewLogin”更改为“Login”,因为我在解决方案中的许多地方调用了此操作。那么mvc路由中是否有其他解决方案?或者这是不可能的,最好是更改我的操作名称?一个简单的解决方案是使用ActionName属性。把这个放在你的行动方法上
[ActionName("Login")]
public ActionResult NewLogin(...)
{
...
}
这将只更改操作名称,如果只希望路径为/login,请使用Route属性:
[Route("login", Name = "Login")]
public ActionResult NewLogin(...)
您可以尝试定义为属性的操作别名,有关详细信息,请参阅文章: ActionNameAttribute重新定义此操作的名称 行动是“观点”。因此,调用此方法以响应 请求/home/view,但不请求/home/viewsome
简单-将其置于上面的默认路线之前:
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.mapmvcattributures()
)
使用这两个选项中的任何一个,您都可以在解决方案中引用一个命名路由(这将允许您在将来必要时更改它):
使用
~/Login
无法满足直接访问的要求。这仍然需要是~/Authentication/Login
@bradcristie thanx,我注意到并修改了答案很好的回答,假设“我在解决方案中的许多地方调用了此操作”意味着“我在C代码中的许多地方直接调用它”。。。重命名操作将中断所有通过UrlHelper.action
(和类似)方法构造URL的位置。@TamimSalem感谢您的回复。我检查了您的解决方案,但在我的解决方案中无法识别路线和名称。我需要为此添加任何额外的名称空间吗?@NithinPaul:您正在运行哪个版本的MVC?属性路由是MVC 5的新功能(以前的版本需要NuGet软件包)。我也尝试了您的解决方案,但我的url现在看起来很像。我不想在url中包含身份验证部分。谢谢您的帮助。然后您需要从路由中隐藏控制器名称:现在我遇到了新问题,我将路由值更改为routes.MapRoute(“默认值”//路由名称”{action}/{id},//URL,带参数new{controller=“Authentication”,action=“BigClientLogin”,id=urlparmeter.Optional}//Parameter defaults);为了避免身份验证部分,但当我尝试以管理员身份登录到我的页面时,我得到了“找不到资源”,因为我的URL是localhost:65423/admin/Dashboard
public class AuthenticationController : Controller
{
[Route("~/Login", Name = "NewLogin")]
public ActionResult NewLogin(...)
{
/* ... */
}
}
@Html.RouteLink("Login", "NewLogin")