c# - 如何使用Windows Azure实现URL重写?

标签 c# asp.net url-rewriting azure query-string

我有一个托管在 Windows Azure 上的 ASP.NET/C# 网站。该网站是一个基于预测的社交网站,主页上有预测摘要的提要。如果您单击摘要,您将使用简单的查询字符串重定向到该预测的详细信息页面。

例如:

http://www.ipredikt.com/details.aspx?id=14

这个特定的预测的标题是“帕丽斯·希尔顿将赢得诺贝尔和平奖”,所以我想做的是为我的网站实现 URL 重写>Azure如下:

http://www.ipredikt.com/predictions/14/paris-hilton-will-win-the-nobel-peace-prize

执行此操作有哪些策略和最佳实践?有人可以给我指点一两篇专门针对 Azure 的优秀文章吗?

连字符标题(“paris-hilton-bla-bla”)实际上只是为了使 URL 更易于阅读;我根本不打算在加载页面方面依赖它。事实上,我可能会允许重复的标题,因为我将依赖 URL 中的预测 ID。

编辑:

忘记提及,我们基于 MVC。我们提出了自己的架构,使用 PageMethods 和 WebMethods 将 JSON 返回给客户端。我们依靠 ASP.NET AJAX 来完成所有 JSON 序列化,并且几乎所有 UI 都是使用 jQuery 在客户端上动态构建的。

编辑:解决方案

现在我已经启动并运行了我的解决方案,我想分享我的解决方案。

我创建了一个新类,如下(从某处逐字复制):

public class WebFormRouteHandler<T> : IRouteHandler where T : IHttpHandler, new()
{
   public string VirtualPath { get; set; }

   public WebFormRouteHandler(string virtualPath)
   {
      this.VirtualPath = virtualPath;
   }

   public IHttpHandler GetHttpHandler(RequestContext requestContext)
   {
      return (VirtualPath != null)
          ? (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(T))
          : new T();
   }
}

我将以下方法添加到 Global.asax 中。实际的方法要长得多(它涵盖了网站中的每个页面)。您会发现我支持以多种不同的方式调用预测页面:使用 id、使用 id + 标题等。(页面的“...fb”版本适用于我网站的 Facebook 应用程序版本,使用不同的母版页。)

  public static void RegisterRoutes(RouteCollection routes)
  {
     // Details : 'predictions' Page
     var routeHandlerDetails = new WebFormRouteHandler<Page>("~/details.aspx");
     var routeHandlerDetailsFb = new WebFormRouteHandler<Page>("~/detailsfb.aspx");

     routes.Add(new Route("predictions/{id}", routeHandlerDetails));
     routes.Add(new Route("predictions/{id}/{title}", routeHandlerDetails));

     routes.Add(new Route("fb/predictions/{id}", routeHandlerDetailsFb));
     routes.Add(new Route("fb/predictions/{id}/{title}", routeHandlerDetailsFb));
   }

...这个方法是从Application_Start()调用的

  void Application_Start(object sender, EventArgs e)
  {
     RegisterRoutes(RouteTable.Routes);
  }

然后我将以下内容添加到 system.webServer block 中的 web.config 中:

   <!-- Added for URL Routing -->
   <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule"
           type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
   </modules>

    <!-- Added for URL Routing -->
    <handlers>
      <add name="UrlRoutingHandler"
           preCondition="integratedMode"
           verb="*"
           path="UrlRouting.axd"
           type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
   </handlers>

我还必须从身份验证中排除虚拟“预测”目录(因为我的非身份验证用户几乎可以访问我们网站的所有部分):

<!-- Url routing -->
<location path="predictions">
   <system.web>
      <authorization>
         <allow users="*" />
      </authorization>
   </system.web>
</location>

最后,我在加载页面时不再依赖 QueryString 字符串参数,因此我必须编写一些新的辅助方法。下面是从新路由 URL 中提取数值的方法(我将对其进行清理,使其只有一个“返回”。):

  public static int GetRouteDataValueAsNumber(HttpRequest request, string propertyName)
  {
     if ((request == null) ||
         (request.RequestContext == null) ||
         (request.RequestContext.RouteData == null) ||
         (request.RequestContext.RouteData.Values[propertyName] == null))
     {
        return -1;
     }

     try
     {
        return System.Convert.ToInt32(request.RequestContext.RouteData.Values[propertyName]);
     }
     catch
     {
     }

     return -1;
  }

现在,当我需要读取路由值(如预测 ID)时,我会执行以下操作:

  long _predictionId = System.Convert.ToInt64(WebAppUtils.GetRouteDataValueAsNumber(Request, "id"));

效果很好!现在,我的网站感觉就像一个具有友好且自记录 URL 的 MVC 应用程序。

哦,最后一件事,您还需要启用 HTTP 重定向,如下所示:

开始 => 控制面板 => 程序 => 打开 Windows 功能 => Internet 信息服务 => 万维网服务 => 通用 HTTP 功能 =>(选中复选框)HTTP 重定向。

最佳答案

实现这一点的最简单方法是使用 System.Web.Routing 程序集的编程方法。

这基本上是通过在 web.config 中包含 UrlRoutingModule 来实现的,并定义基于匹配路由解析目标页面的模式。如果您熟悉 ASP.NET MVC,那么您以前使用过这种路由策略,但 MVC 并不是必须使用路由。

以下是一些可帮助您入门的资源:

关于 Windows Azure ...

如果您采用这种方法,那么您是否使用 Windows Azure 并不重要。然而,我发现了一个article by Michael Kennedy called ASP.NET Routing in Windows Azure Using WebForms ,解释如何在 Windows Azure 上轻松部署此类解决方案。这篇文章甚至有一个sample project for download .

关于c# - 如何使用Windows Azure实现URL重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397925/

相关文章:

php - 我们如何将看起来像 cakephp/pages/1 的 cakephp url 转换为 cakephp/about-us?

c# - 检测服务器和SQL Server错误并显示错误页面

c# - 如何根据ID删除元素?

c# - 如何在 UML 中表示索引或参数化属性?

c# - 如何向现有的依赖属性回调添加逻辑?

c# - ASP.NET Core Web 应用程序 - 错误 -4077 ECONNRESET 连接被对等方重置

c# - 如何为组合框获取我的数据源一次?

asp.net - 逐字说明符 : @ 后预期的关键字、标识符或字符串

asp.net - 哪里有服务器变量或 <allowedServerVariables> 的列表?

apache将一个目录下的所有hash标签重写为斜杠标签