Best practice for http redirection for Windows Azure

别等时光非礼了梦想. 提交于 2019-12-02 16:49:15
user94559

You might want to instead use the IIS rewrite module (seems "cleaner"). Here's a blog post that shows how to do this: http://weblogs.asp.net/owscott/archive/2009/11/30/iis-url-rewrite-redirect-multiple-domain-names-to-one.aspx. (You'll just need to put the relevant markup in web.config.)

An example rule you could use is:

    <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>

This is what I did:

We have a base controller class we use for all our controllers, we now override:

 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);
        }
    }

And added the following class:

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 */);
        }

    }
}

The reasoning is that I want a permanent redirect (not a temporary one) so the search engines correct all the bad links.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!