Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在MVC4中更改URL格式?_C#_Asp.net Mvc - Fatal编程技术网

C# 如何在MVC4中更改URL格式?

C# 如何在MVC4中更改URL格式?,c#,asp.net-mvc,C#,Asp.net Mvc,当前我的URL如下所示: http://localhost:9737/ProfileEdit?writerId=4 http://localhost:9737/ProfileEdit/4 routes.MapRoute( name: "ProfileEdit", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "P

当前我的URL如下所示:

http://localhost:9737/ProfileEdit?writerId=4
http://localhost:9737/ProfileEdit/4
routes.MapRoute(
           name: "ProfileEdit",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Home", action = "ProfileEdit", writerId = UrlParameter.Optional }
       );
但我希望它是这样的:

http://localhost:9737/ProfileEdit?writerId=4
http://localhost:9737/ProfileEdit/4
routes.MapRoute(
           name: "ProfileEdit",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Home", action = "ProfileEdit", writerId = UrlParameter.Optional }
       );
这是我的行动签名:

public ActionResult ProfileEdit(long writerId)
我尝试在RouteConfig文件中添加新路由,如下所示:

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

但是没有运气。。那么如何更改URL格式呢?

路由将参数定义为id:

但您使用的是writerId:

将路由更改为匹配:

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

请注意,这将有助于在使用该路由的每个URL上进行此更改。

您可以添加路由属性:

routes.MapRoute(
           name: "ProfileEdit",
           url: "ProfileEdit/{id}",
           defaults: new { controller = "Home", action = "ProfileEdit"}
       );
[Route("ProfileEdit/{writerId}")]
public ActionResult ProfileEdit(long writerId)
有两种方法可以做到这一点:

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

执行相反的操作并更改操作中的参数名称,以匹配路由值public ActionResult ProfileEditlong id

编辑

如果要为多个参数指定相同的参数,还需要在管线中指定这些参数:

routes.MapRoute 档案编辑, {controller}/{action}/{writerId}/{otherParameter}, 新建{controller=Home,action=ProfileEdit,writerId=,otherParameter=}


对不起,它坏了。它不断给出这个错误:参数字典包含参数'writerId'@TahreemIqbal:哪个URL的空条目?@TahreemIqbal:该URL中不也应该有控制器名称吗?这是代码:routes.MapRoute name:ProfileEdit,URL:{controller}/{action}/{writerId},默认值:新建{controller=Home,action=ProfileEdit,writerId=UrlParameter.Optional};路由属性位于System.Web.Http中。尝试使用System.Web.Http添加;在控制器的开始部分,它通过将操作参数更改为public ActionResult ProfileEditlong id来工作,我不明白为什么它不能与writerid一起工作。对于多个参数,我该怎么办?谢谢您的回答,但这只解决了我一半的问题。我无法更改URL中多个参数的格式