代码之家  ›  专栏  ›  技术社区  ›  Sam Saffron James Allen

Windows Azure HTTP重定向的最佳实践

  •  16
  • Sam Saffron James Allen  · 技术社区  · 14 年前

    我有一个叫:

    • http://myapp.cloudapp.net

    当然,这个网址有点难看,所以我 set up a CNAME 那点 http://www.myapp.com 到Azure URL。

    到这里一切都很好,但有一个障碍。

    http://myapp.cloudapp.net 已经泄露出去了,现在被谷歌编入索引,生活在其他网站上。

    我想永久性地将myapp.cloudapp.net的任何请求重定向到www.myapp.com的新主页。

    我所拥有的网站是用MVC.NET 2.0编码的,因为这是一个Azure应用程序,没有用于访问IIS的UI,所有工作都需要在应用程序代码或web.config中完成。

    在web.config或全局控制器中设置永久重定向的干净方法是什么?

    2 回复  |  直到 12 年前
        1
  •  18
  •   Sam Saffron James Allen    14 年前

    您可能希望使用IIS重写模块(看起来更“干净”)。以下是一篇博客文章,展示了如何做到这一点: http://weblogs.asp.net/owscott/archive/2009/11/30/iis-url-rewrite-redirect-multiple-domain-names-to-one.aspx . (您只需要将相关标记放入web.config中。)

    您可以使用的一个示例规则是:

        <rule name="cloudexchange" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="cloudexchange.cloudapp.net" />
            </conditions>
            <action type="Redirect" url="http://odata.stackexchange.com/{R:0}" />
        </rule>
    
        2
  •  5
  •   Sam Saffron James Allen    14 年前

    我就是这样做的:

    我们有一个用于所有控制器的基本控制器类,现在我们覆盖:

     protected override void OnActionExecuted(ActionExecutedContext filterContext) {
    
            var host = filterContext.HttpContext.Request.Headers["Host"];
    
            if (host != null && host.StartsWith("cloudexchange.cloudapp.net")) {
                filterContext.Result = new RedirectPermanentResult("http://odata.stackexchange.com" + filterContext.HttpContext.Request.RawUrl);
            } else
            {
                base.OnActionExecuted(filterContext);
            }
        }
    

    并添加了以下类:

    namespace StackExchange.DataExplorer.Helpers
    {
        public class RedirectPermanentResult : ActionResult {
    
            public RedirectPermanentResult(string url) {
                if (String.IsNullOrEmpty(url)) {
                    throw new ArgumentException("url should not be empty");
                }
    
                Url = url;
            }
    
    
            public string Url {
                get;
                private set;
            }
    
            public override void ExecuteResult(ControllerContext context) {
                if (context == null) {
                    throw new ArgumentNullException("context");
                }
                if (context.IsChildAction) {
                    throw new InvalidOperationException("You can not redirect in child actions");
                }
    
                string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);
                context.Controller.TempData.Keep();
                context.HttpContext.Response.RedirectPermanent(destinationUrl, false /* endResponse */);
            }
    
        }
    }
    

    原因是我想要一个永久性的重定向(而不是临时重定向),这样搜索引擎就可以纠正所有的坏链接。