【问题标题】:How to change my web-forms url from "Pages/Games.aspx?page=1" to "games/1"?如何将我的网络表单 URL 从“Pages/Games.aspx?page=1”更改为“games/1”?
【发布时间】:2019-04-01 18:10:24
【问题描述】:

我使用 VS 2017 我有简单的项目结构。

我正在尝试使用老式网络表单为我的Games.aspx 添加简单的路由。根据MSDN,它看起来像这样。只需在App_Code 文件夹中创建新的RouteConfig 类(这是我定义路由的地方)

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("", "games/{page}", "~/Games.aspx");
    }
}

并在 Global.asax Start 方法中调用该静态方法。

    public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

但是当我启动项目时,我得到了 Not found 错误:

当我像Pages/Games.aspx?page=1 一样直接调用它时,我的Games.aspx 可以工作,但我不想在我的网址中使用这些东西。我试图调试 Start 方法,但它似乎是由 IIS 或其他什么编译的。那么,我哪里错了?

【问题讨论】:

  • @NabeelKhan,对于这么简单的任务来说,这有点太复杂了。
  • routes.MapPageRoute("", "games/{page}", "~/Games.aspx");您是否可能错过了这里的页面,例如 routes.MapPageRoute("", "games/{page}", "~/Pages/Games.aspx");
  • @SehaxX,不。事实并非如此。我什至尝试了整个路径。那没有用。

标签: c# asp.net .net webforms routing


【解决方案1】:

我无法复制您的代码,因为将 RouteConfig 类放入 App_Code 不会让我在 Global.asmx 中引用它。我所做的是将映射路线的方法放在我的Gloabal.asmx中,现在它看起来像这样。

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
       RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("", "games/{page}", "~/Games.aspx");
    }
}

当我注释掉 RegisterRoutes() 方法时,我会得到同样的错误。试试这个方法蚂蚁让我知道它是否有帮助。 此外,要获取 Game.aspx 中传递的值,您应该使用此 Page.RouteData.Values["page"]

【讨论】:

  • 我试过了,很遗憾没用。但是感谢您的方法。
  • 我认为这是将路由更改为routes.MapPageRoute("", "games/{page}", "~/Pages/Games.aspx"); 并使用Page.RouteData.Values["page"] 的组合。
【解决方案2】:

您也许可以使用 URL 重写模块来处理这个问题:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="RewriteGames" stopProcessing="true">
                <match url="^games/(\d+)" />
                <action type="Rewrite" url="Pages/Games.aspx?page={R:1}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

正如@a.bajorinas 所避免的,如果您在路由中捕获page 参数,那么您必须修改代码以使用Page.RouteData 而不是Request.QueryString。这真的不是什么大的变化。但是,如果您只想更改 URL,使用下面的代码在 web.config 中执行此操作可能是最简单的。

【讨论】:

  • 谢谢,严格来说这不是我想要的,但它成功了。
猜你喜欢
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多