【问题标题】:ASP.NET Routing to pass query string to the pageASP.NET 路由将查询字符串传递到页面
【发布时间】:2011-08-15 00:50:50
【问题描述】:

我正在使用 ASP.NET 路由将 URL 映射到我网站的任意数量的部分。尽管我希望有不同的 URL,但它们都将由同一页面处理。例如

http://site.com/blog 用于我的blog 部分
http://site.com/mysection 用于mysection 等。

这些部分可以有任意数量,但它们都将由Lister.aspx 处理。 我还有另一个处理内容的页面,名为ContentView.aspx,它展示了内容。我的路线如下:(猫是类别列表)

cats.ForEach(c =>
        {
            table.Add(new Route(c.ShortName, new PageRouteHandler("~/Lister.aspx?cat=" + c.ID), ));
            table.Add(new Route(c.ShortName + "/{id}", new PageRouteHandler("~/ContentView.aspx")));
            table.Add(new Route(c.ShortName + "/{id}/{title}", new PageRouteHandler("~/ContentView.aspx")));
        });

假设我有一篇 ID 为 123 标题为 hello 的博文:
用户可以通过http://site.com/blog/123/hello访问它
他们也可以只使用 ID http://site.com/blog/123
正如您可能猜到的那样,我希望http://site.com/blog 指向列表页面而不是内容查看器,并且我还需要类别 ID 来区分哪个类别(blogmycategory 或其他任何动态创建的内容)我应该显示。我正在尝试将类别 ID 传递给查询字符串,调用列表页面,但没有查询字符串。为什么会出现这种行为,如何将我的类别 ID 发送到列表页面?

【问题讨论】:

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


    【解决方案1】:

    我建议创建您自己的实现 IRouteHandler 的 RouteHandler,然后您可以将单独的参数传递给它的构造函数(类别 ID)。

    然后在 GetHttpHandler 中,您可以使用 HttpContext 将该 ID 传递给页面。

    类似:

    public class CategoryRouteHandler : IRouteHandler 
    {
       private string _virtualPath;
       private string _category;
    
       public CategoryRouteHandler(string virtualPath, string category)
       {
           _virtualPath = virtualPath;
           _category = category;
       }
    
       public IHttpHandler GetHttpHandler(RequestContext requestContext) 
       {
            var handler = BuildManager.CreateInstanceFromVirtualPath(
                _virtualPath, typeof(Page)) as IDefaultHttpHandler;
    
            HttpContext.Current.Items["Category"] = _category;
    
            return handler;
       }
    } 
    

    那么你可以使用:

    table.Add(new Route(c.ShortName, new CategoryRouteHandler("~/Lister.aspx", c.ID), ));
    

    从Lister的代码你可以访问HttpContext.Current.Items["Category"]

    编辑:更新以修复代码,抱歉我第一次没有测试。

    【讨论】:

    • 您的代码包含两个错误:CategoryRouteHandler 的基类是什么,GetHttpHandler 方法返回什么?我试图通过使用 PageRouteHandler 作为基类并返回当前的 IHttpHandler 来使其工作,但无法将值传递给页面。
    猜你喜欢
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多