【问题标题】:ASPMvc Routing Issues with legacy url旧版 url 的 ASP Mvc 路由问题
【发布时间】:2011-05-31 10:56:51
【问题描述】:

我有一个无法更改的旧 url,它在页面上输出,现在需要发布到页面的新 MVC 版本:

http://somesite.com/somepage?some-guid=xxxx-xxxx

现在我正在尝试将其映射到一个新控制器,但我需要将 some-guid 放入我的控制器:

public class MyController : Controller
{
    [HttpGet]
    public ActionResult DisplaySomething(Guid myGuid)
    {
        var someResult = DoSomethingWithAGuid(myGuid);
        ...
    }
}

我可以随心所欲地更改控制器和路由,但是旧版 url 不能更改。所以我对如何访问 some-guid 感到有些困惑。

我尝试使用 ?some-guid={myGuid} 进行路由,但路由不喜欢 ?,所以我尝试让它自动绑定,但由于它包含连字符,因此它似乎没有绑定。我想知道是否有任何类型的属性可以用来暗示它应该从查询字符串的一部分绑定...

任何帮助都会很棒...

【问题讨论】:

  • 注意事项:Action 中方法参数的名称非常重要,必须与 URL 中传递的查询参数匹配。如果这些不同,则不会发生自动数据绑定 - 路由系统向 RouteData 集合查询键,这些键本质上是方法中的参数名称。如果找到该条目(仅当查询字符串参数与方法参数名称匹配时才会发生),则该值将自动绑定到方法参数。在您的情况下,URL 应该有查询字符串“myGuid”而不是“some-guid”
  • 是的,但是由于 some-guid 不是一个有效的名称,我认为它可能会做 webforms 过去对无效元素名称所做的事情,只是从变量中去掉“-”,但它没有似乎没有。据我所知,MVC 足够聪明,可以知道您传入的是什么类型以及您期望什么类型,然后将它们结合起来,尽管我可能弄错了。

标签: asp.net-mvc url-routing query-string


【解决方案1】:

我原以为你会做这样的路线..

routes.MapRoute(
                "RouteName", // Name the route
                "somepage/{some-guid}", // the Url
                new { controller = "MyController", action = "DisplaySomething", some-guid = UrlParameter.Optional }
            );

URL 的 {some-guid} 部分与您的 url 参数匹配并将其传递给控制器​​。

所以,如果你有这样的行为:

public ActionResult DisplaySomething(Guid some-guid)
    {
        var someResult = DoSomethingWithAGuid(some-guid);
        ...
    }

试一试,看看你的进展如何..

【讨论】:

    【解决方案2】:
    routes.MapRoute(
      "Somepage", // Route name
      "simepage", // URL with parameters
      new { controller = "MyController", action = "DisplaySomething"
    );
    

    然后在你的控制器中:

    public class MyController : Controller {
        public ActionResult DisplaySomething(Guid myGuid)
        {
            var someResult = DoSomethingWithAGuid(myGuid);
            ...
        }
    }
    

    【讨论】:

    • 它如何知道上面示例中的 myGuid 是什么?因为上面示例中查询字符串上的变量称为 some-guid。理想的路由是“/somepage/xxxx-xxxx-xxxx-...”,因此可以将 Guid 作为路由的一部分放入并从中提取变量,但是如前所述,我无法更改 url.. .
    • 可以用Url Rewriting把它变成上面的格式吗? iis.net/download/URLRewrite
    【解决方案3】:

    试试这个:

    routes.MapRoute("SomePageRoute","Somepage", 
       new { controller = "MyController", action = "DisplaySomething" });
    

    然后在你的控制器中:

    public ActionResult DisplaySomething() {
       Guid sGuid = new Guid(Request.QueryString["some-guid"].ToString());
    }
    

    【讨论】:

    • Guid some-guid 不是有效的 c#。第一个解决方案可能会起作用,但它会切断我理想情况下想要使用的自动装订器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多