gpt4 book ai didi

asp.net-mvc-3 - 使用和不使用查询字符串路由遗留请求

转载 作者:行者123 更新时间:2023-12-04 15:14:38 26 4
gpt4 key购买 nike

(开始之前:我知道 thisthis 。如果可能的话,我想为稍微更具体的问题找到更简洁的解决方案)

我正在 MVC 中重写一个旧的 Webforms 应用程序。像往常一样,不应破坏任何永久链接。

我正在使用标准 {controller}/{action}/{id}路线。传统路径通常是 SomePage.aspx?ID=xxx ,我有一个特殊情况,其中 Foo.aspxBar 的列表(新 URL: /Bar /Bar/Index )和
Foo.aspx?ID=xxxBar详细信息(新网址:/Bar/View/xxx )

一种可能的解决方法是在 Default MapRoute 之前添加以下内容:

routes.MapRoute("Bar View", "Foo.aspx",
new { controller = "Bar", action = "View" });

然后在 BarController 中定义相应的 Action :
public ActionResult View(int? id)
{
if (id == null)
return RedirectToAction("Index");
return View();
}

这有两个问题:
  • 现在,如果我创建一个 ActionLink,它将使用旧格式
  • 我想在 route 处理这个问题;使 id 可以为空并在 Controller 中重定向是错误的

  • 我可以手动映射旧 URL(我不需要通用解决方案,只有大约 8 页)

    这是一个新项目,所以我没有任何关系。

    最佳答案

    我能够基于 Dangerous' idea 解决这个问题加上基于 this answer 的约束.

    我的新路由表是:

    routes.MapRoute("Bar", "Bar/{action}/{id}",
    new
    {
    controller = "Bar",
    action = "Index",
    id = UrlParameter.Optional
    });
    routes.MapRoute("Bar View", "Foo.aspx",
    new {controller = "Bar", action = "View"},
    new {id = new QueryStringConstraint()});
    routes.MapRoute("Bar Index", "Foo.aspx",
    new { controller = "Bar", action = "Index" });
    routes.MapRoute("Default", /*...*/);

    QueryStringConstraint 再简单不过了:
    public class QueryStringConstraint : IRouteConstraint
    {
    public bool Match(HttpContextBase httpContext, Route route,
    string parameterName, RouteValueDictionary values,
    RouteDirection routeDirection)
    {
    return httpContext.Request.QueryString.AllKeys
    .Contains(parameterName, StringComparer.InvariantCultureIgnoreCase);
    }
    }

    关于asp.net-mvc-3 - 使用和不使用查询字符串路由遗留请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9162925/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com