如何在 MVC 4 中更改 URL 格式

本文关键字:URL 格式 MVC | 更新日期: 2023-09-27 18:37:25

目前我的URL看起来像这样:

http://localhost:9737/ProfileEdit?writerId=4

但我希望它是这样的:

http://localhost:9737/ProfileEdit/4

这是我的操作签名:

public ActionResult ProfileEdit(long writerId)

我尝试在 RouteConfig 文件中添加新路由,如下所示:

routes.MapRoute(
           name: "ProfileEdit",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Home", action = "ProfileEdit", writerId = UrlParameter.Optional }
       );

但没有运气..那么我该如何更改URL格式呢?

如何在 MVC 4 中更改 URL 格式

路由将参数定义为id

url: "{controller}/{action}/{id}"

但是您正在使用writerId

http://localhost:9737/ProfileEdit?writerId=4

更改路线以匹配:

url: "{controller}/{action}/{writerId}"

请注意,这将促进使用该路由的每个 URL 上的此更改。

您可以添加路由属性:

[Route("ProfileEdit/{writerId}")]
public ActionResult ProfileEdit(long writerId)

您有两种方法可以执行此操作:

  1. 更改路由值以匹配操作url: "{controller}/{action}/{writerId}"中的参数名称。

  2. 执行相反的操作,更改操作中的参数名称以匹配路由值public ActionResult ProfileEdit(long id)

编辑

如果您希望多个参数相同,则还需要在路由中指定它们:

routes.MapRoute( "ProfileEdit", "{controller}/{action}/{writerId}/{otherParameter}", new { controller = "Home", action = "ProfileEdit", writerId = "", otherParameter = "" });

routes.MapRoute(
           name: "ProfileEdit",
           url: "ProfileEdit/{id}",
           defaults: new { controller = "Home", action = "ProfileEdit"}
       );