URL从查询字符串中的URL重写为更友好的URL

时间:2014-10-31 06:03:50

标签: asp.net asp.net-mvc-4 url url-rewriting

我在重写我的网址时遇到了问题。截至目前,我的网址是querystring的形式,传递参数。现在我想将该网址更改为更友好的网址 。让我举个例子

http://localhost:59423/SomeController/SomeActionMethod?Id=7

类似

http://localhost:59423/SomeController/SomeActionMethod/7

或类似的东西。

现在我现在必须在route.config文件中进行修改但是我没有得到什么修改

我添加了类似的内容

     routes.MapRoute(
                 name: "SomeName",
                 url: "SomeController/SomeActionMethod/{Id}",
                 defaults: new { controller = "SomeController", action ="SomeActionMethod" });

如果我输入

,我现在可以访问该视图
   http://localhost:59423/SomeController/SomeActionMethod/7

但是当我把网址设为

http://localhost:59423/SomeController/SomeActionMethod?Id=7

这应自动更改为

http://localhost:59423/SomeController/SomeActionMethod/7

它应该自动更改为正确的URL。如果不是那么怎么办?如果是,那么我错过了因为它没有改变

行动方法

         public ActionResult SomeActionMethod(string Id)
    {

        return View((Id));
    }

2 个答案:

答案 0 :(得分:1)

经过多次试验和错误后,我找到了我要找的东西

正如我在我的问题中已经提到的,你可以在route.config文件中添加map.route

像这样的东西

routes.MapRoute(
             name: "SomeName",
             url: "SomeController/SomeActionMethod/{Id}",
             defaults: new { controller = "SomeController", action ="SomeActionMethod" });

或者如果你在" SomeAction方法"中有两个参数。然后

routes.MapRoute(
             name: "SomeName",
             url: "SomeController/SomeActionMethod/{Id}/{parameter2}",
             defaults: new { controller = "SomeController", action ="SomeActionMethod" });

现在你必须拥有一个查询字符串。像这样的东西

document.location = "/SomeController/SomeActionMethod?Id=" + SomeId + "&parameter2=" + SomeParameter;

现在,由于您已经编写了map.route,因此可以将上述查询字符串更改为此类

"/SomeController/SomeActionMethod/" + SomeId + "/" + SomeParameter;

每当调用此URL时,它将使用您在route.config文件中提供的路由信息​​进行映射,如上所述。并且根据它知道你在" SomeActionMethod"中有两个参数{Id}和{parameter2}。 ,因此它会自动呈现动作方法并传递变量。

因此,您可以消除在网址中包含查询字符串的需要,并且实际上有更友好的网址,这是基于slaks" /"。

希望它可以帮助任何人寻找同样的问题。

答案 1 :(得分:0)

通过使用IIS URL重写,您可以根据需要进行配置。 URL Rewrite