RedirectPermanent() public method

public RedirectPermanent ( string url ) : void
url string
return void
Example #1
0
		/// <summary>
		/// 写入到http回应
		/// </summary>
		/// <param name="response"></param>
		public void WriteResponse(HttpResponse response) {
			if (Permanent) {
				response.RedirectPermanent(Url);
			} else {
				response.Redirect(Url);
			}
		}
 private static void Redirect(HttpResponse response, string url, bool permanent)
 {
     if (permanent) {
         response.RedirectPermanent(url, true);
     }
     else {
         response.Redirect(url, false);
     }
 }
Example #3
0
        private void ExportDivContentToPDF()
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            try
            {
                // create an API client instance
                string          userName = ConfigurationManager.AppSettings["pdfcrowdUsername"].ToString();
                string          APIKey   = ConfigurationManager.AppSettings["pdfcrowdAPIKey"].ToString();
                pdfcrowd.Client client   = new pdfcrowd.Client(userName, APIKey);

                // convert a web page and write the generated PDF to a memory stream
                MemoryStream Stream = new MemoryStream();
                //client.convertURI("http://www.google.com", Stream);

                // set HTTP response headers
                Response.Clear();
                Response.AddHeader("Content-Type", "application/pdf");
                Response.AddHeader("Cache-Control", "max-age=0");
                Response.AddHeader("Accept-Ranges", "none");
                Response.AddHeader("Content-Disposition", "attachment; filename=TigerReservePdfExport.pdf");
                System.IO.StringWriter       stringWrite1 = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite1   = new HtmlTextWriter(stringWrite1);
                MainContent.RenderControl(htmlWrite1);
                client.convertHtml(stringWrite1.ToString(), Stream);
                // send the generated PDF
                Stream.WriteTo(Response.OutputStream);
                Stream.Close();
                Response.Flush();
                Response.End();
            }
            catch (pdfcrowd.Error why)
            {
                LogHandler.LogFatal((why.InnerException != null ? why.InnerException.Message : why.Message), why, this.GetType());
                Response.RedirectPermanent("~/ErrorPage.aspx", false);
                Response.Write(why.ToString());
            }
        }
 public override void RedirectPermanent(String url)
 {
     _httpResponse.RedirectPermanent(url);
 }
Example #5
0
 public override void RedirectPermanent(string url)
 {
     w.RedirectPermanent(url);
 }
        private static bool CheckForTabExternalForwardOrRedirect(HttpContext context, 
                                                                    ref UrlAction result,
                                                                    HttpResponse response, 
                                                                    FriendlyUrlSettings settings,
                                                                    Guid parentTraceId)
        {
            bool finished = false;
            HttpRequest request = null;
            if (context != null)
            {
                request = context.Request;
            }

            try
            {
                            //check for external forwarding or a permanent redirect request
            //592 : check for permanent redirect (823 : moved location from 'checkForRedirects')
            if (result.TabId > -1 && result.PortalId > -1 &&
                (settings.ForwardExternalUrlsType != DNNPageForwardType.NoForward ||
                 result.Reason == RedirectReason.Tab_Permanent_Redirect))
            {
                bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLower().Contains("&ctl=tab"));
                //594 : do not redirect settings pages for external urls
                if (allowRedirect)
                {
                    TabInfo tab;
                    allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings);
                    if (allowRedirect)
                    {
                        //772 : not redirecting file type Urls when requested.
                        bool permanentRedirect = false;
                        string redirectUrl = null;
                        string cleanPath = null;
                        bool doRedirect = false;
                        switch (tab.TabType)
                        {
                            case TabType.File:
                                //have to fudge in a portal settings object for this to work - shortcoming of LinkClick URl generation
                                var portalSettings = new PortalSettings(result.TabId, result.PortalAlias);
                                if (context != null)
                                {
                                    context.Items.Add("PortalSettings", portalSettings);
                                    result.Reason = RedirectReason.File_Url;
                                    string fileUrl = Globals.LinkClick(tab.Url, tab.TabID, -1);
                                    context.Items.Remove("PortalSettings");
                                    //take back out again, because it will be done further downstream
                                    //do a check to make sure we're not repeating the Url again, because the tabid is set but we don't want to touch
                                    //a linkclick url
                                    if (!result.OriginalPathNoAlias.EndsWith(HttpUtility.UrlDecode(fileUrl), true, CultureInfo.InvariantCulture))
                                    {
                                        redirectUrl = fileUrl;
                                    }
                                }
                                if (redirectUrl != null)
                                {
                                    doRedirect = true;
                                }
                                break;
                            case TabType.Url:
                                result.Reason = RedirectReason.Tab_External_Url;
                                redirectUrl = tab.Url;
                                if (redirectUrl != null)
                                {
                                    doRedirect = true;
                                    if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301)
                                    {
                                        result.Action = ActionType.Redirect301;
                                        result.Reason = RedirectReason.Tab_External_Url;
                                    }
                                    else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302)
                                    {
                                        result.Action = ActionType.Redirect302;
                                        result.Reason = RedirectReason.Tab_External_Url;
                                    }
                                }
                                break;
                            case TabType.Tab:
                                // if a tabType.tab is specified, it's either an external url or a permanent redirect

                                //get the redirect path of the specific tab, as long as we have a valid request to work from
                                if (request != null)
                                {
                                    //get the rewrite or requested path in a clean format, suitable for input to the friendly url provider
                                    cleanPath = RewriteController.GetRewriteOrRequestedPath(result, request.Url);
                                    //727 prevent redirectLoop with do301 in querystring
                                    if (result.Action == ActionType.Redirect301 ||
                                        result.Action == ActionType.Redirect302)
                                    {
                                        cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath,
                                                                                           request.QueryString);
                                    }
                                    //get the redirect Url from the friendly url provider using the tab, path and settings
                                    redirectUrl = RedirectController.GetTabRedirectUrl(tab, settings, cleanPath, result,
                                                                                       out permanentRedirect,
                                                                                       parentTraceId);
                                }
                                //check to make sure there isn't a blank redirect Url
                                if (redirectUrl == null)
                                {
                                    //problem : no redirect Url to redirect to
                                    //solution : cancel the redirect
                                    string message = "Permanent Redirect chosen for Tab " +
                                                     tab.TabPath.Replace("//", "/") +
                                                     " but forwarding Url was not valid";
                                    RedirectController.CancelRedirect(ref result, context, settings, message);
                                }
                                else
                                {
                                    //if there was a redirect Url, set the redirect action and set the type of redirect going to use
                                    doRedirect = true;
                                    if (permanentRedirect)
                                    {
                                        result.Action = ActionType.Redirect301;
                                        result.Reason = RedirectReason.Tab_Permanent_Redirect;
                                        //should be already set, anyway
                                        result.RewritePath = cleanPath;
                                    }
                                    else
                                    {
                                        //not a permanent redirect, check if the page forwarding is set
                                        if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301)
                                        {
                                            result.Action = ActionType.Redirect301;
                                            result.Reason = RedirectReason.Tab_External_Url;
                                        }
                                        else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302)
                                        {
                                            result.Action = ActionType.Redirect302;
                                            result.Reason = RedirectReason.Tab_External_Url;
                                        }
                                    }
                                }
                                break;
                            default:
                                //only concern here is if permanent redirect is requested, but there is no external url specified
                                if (result.Reason == RedirectReason.Tab_Permanent_Redirect)
                                {
                                    bool permRedirect = tab.PermanentRedirect;
                                    if (permRedirect)
                                    {
                                        //problem : permanent redirect marked, but no forwarding url supplied
                                        //solution : cancel redirect
                                        string message = "Permanent Redirect chosen for Tab " +
                                                         tab.TabPath.Replace("//", "/") +
                                                         " but no forwarding Url Supplied";
                                        RedirectController.CancelRedirect(ref result, context, settings, message);
                                    }
                                }
                                break;
                        }

                        //do the redirect we have specified
                        if (doRedirect &&
                            (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302))
                        {
                            result.FinalUrl = redirectUrl;
                            if (result.Action == ActionType.Redirect301)
                            {
                                if (response != null)
                                {
                                    //perform a 301 redirect to the external url of the tab
                                    response.AppendHeader("X-Redirect-Reason",
                                                          result.Reason.ToString().Replace("_", " ") + " Requested");
                                    response.RedirectPermanent(result.FinalUrl);
                                }
                            }
                            else
                            {
                                if (result.Action == ActionType.Redirect302)
                                {
                                    if (response != null)
                                    {
                                        //perform a 301 redirect to the external url of the tab
                                        response.AppendHeader("X-Redirect-Reason",
                                                              result.Reason.ToString().Replace("_", " ") + " Requested");
                                        response.Redirect(result.FinalUrl);
                                    }
                                }
                            }
                            finished = true;
                        }
                    }
                }
            }

            }
            catch (ThreadAbortException)
            {
                //do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block.  This is the highest
                //level try/catch block, so we handle it here.
            }
            return finished;
        }
Example #7
0
        private void ProcessRequestInner(HttpContext context, HttpRequest request, HttpResponse response)
        {
            if (request.Path == "/null") {
                return;
            }

            // If session
            if (request.Path.Substr(0, 2) == "/(" && request.Path.Substr(24, 1) == ")") {
                // Find sessionId
                Xid sessionId;
                try {
                    sessionId = new Xid(request.Path.Substr(2, 22));
                } catch (FormatException) {
                    SendJsonFailure("Amos3.Session", "Session ID paramater malformed");
                    return;
                }

                // Find session
                Session session;
                if (!Session.TryGet(sessionId, out session)) {
                    SendJsonFailure("Amos3.Session.Expired", "Session has expired");
                    return;
                }

                // Determine if Trigger or RPC
                if (request.Path.CountCharacter('/') == 1) {
                    // RPC
                    RpcHandler(session, request.InputStream, request, response);
                } else {
                    // Trigger
                    TriggerHandler(session, request.Url.Segments[2], request, response);
                }
                return;
            }

            // Find client IP
            var ip = context.Request.ServerVariables["REMOTE_ADDR"];
            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            // Handle crawlers
            if (null != context.Request.QueryString["_escaped_fragment_"] && context.Request.QueryString["_escaped_fragment_"].Length > 1) {
                // Mark IP as a crawler for the next 30 seconds
                crawlers[ip] = DateTime.Now;

                context.Response.Status = "301 Moved Permanently";
                context.Response.AddHeader("Location", (RequireSecureHttp ? "https://" : "http://") + context.Request.ServerVariables["SERVER_NAME"] + context.Request.QueryString["_escaped_fragment_"]);
                return;
            }

            if (crawlers.ContainsKey(ip) ||
                context.Request.UserAgent.IndexOf("facebookexternalhit") != -1 ||
                context.Request.UserAgent.IndexOf("Feedfetcher-Google") != -1 ||
                context.Request.UserAgent.IndexOf("bingbot") != -1 ||
                context.Request.UserAgent.IndexOf("Googlebot") != -1 ||
                context.Request.UserAgent.IndexOf("Slurp") != -1 ||
                context.Request.UserAgent.IndexOf("search.msn.com") != -1 ||
                context.Request.UserAgent.IndexOf("nutch") != -1 ||
                context.Request.UserAgent.IndexOf("simpy") != -1 ||
                context.Request.UserAgent.IndexOf("bot") != -1 ||
                context.Request.UserAgent.IndexOf("ASPSeek") != -1 ||
                context.Request.UserAgent.IndexOf("crawler") != -1 ||
                context.Request.UserAgent.IndexOf("msnbot") != -1 ||
                context.Request.UserAgent.IndexOf("ASPSeek") != -1 ||
                context.Request.UserAgent.IndexOf("Libwww-perl") != -1 ||
                context.Request.UserAgent.IndexOf("FAST") != -1 ||
                context.Request.UserAgent.IndexOf("Baidu") != -1 ||
                context.Request.UserAgent.IndexOf("YandexBot") != -1
                ) {
                // Add static content
                StaticRender(context.Request.Url.AbsolutePath.Substring(1), context);

                // Remove old Crawlers
                var limit = DateTime.Now.AddSeconds(-30);
                var remove = new List<string>();
                foreach (var crawler in crawlers) {
                    if (crawler.Value < limit) remove.Add(crawler.Key);
                }
                foreach (var crawlerip in remove) {
                    crawlers.Remove(crawlerip);
                }

                return;
            }

            // If downloading document
            if (request.Path.ToLower().StartsWith("/downloaddocument")) {
                DocumentDownload.GetDocument(request);
                return;
            }

            // If frame
            if (request.Path == "/delegateframe") {
                // Create a new session
                var session = Session.Create(request, this, new EnvelopeHandlerMulti());

                // Send frame
                DelegateFrame.SendFrame(response, session);
                return;
            }

            // If robots
            if (request.Path.ToUpperInvariant() == "/ROBOTS.TXT") {
                Robots(context);
                return;
            }

            // Check we have WAR
            if (null == HttpRootFile) {
                response.Write("No WAR.");
                return;
            }

            // If needed, upgrade the connection to HTTPS
            if (RequireSecureHttp && !request.IsSecureConnection && string.Compare(request.Url.Host, "localhost", true) != 0) {
                var url = request.Url.ToString();
                url = "https" + url.Substr(url.IndexOf(":"));
                response.Redirect(url);
                return;
            }

            // Find target details
            var path = request.Path == "/" ? "/index.html" : request.Path;

            // Stop hacks
            if (path.IndexOf("..") > -1 || path.IndexOf("//") > -1 || path.IndexOf("\\\\") > -1) {
                response.SendFailure(HttpStatusCode.NotFound, "Denied.");
            }

            // Get content
            byte[] page;
            lock (WebCache) {
                // Read cache
                page = WebCache[path] as byte[];

                // If cache miss..
                if (null == page) {

                    // Open WAR file
                    if (null == HttpRoot) {
                        try {
                            HttpRoot = ZipFile.Read(HttpRootFile.FullName);
                        } catch (Exception ex) {
                            // Log the exception
                            LogException(ex, "Variant-HttpRoot", Ids.System);

                            // Warn users that we're updating
                            response.Write("We're currently updating our content. Hang tight - the site will be back shortly!");
                            return;
                        }

                        if (null == HttpRoot["/index.html"]) {
                            throw new Exception("Missing '/index.html' in WAR");
                        }
                    }

                    // Open file
                    ZipEntry file;
                    if (null == (file = HttpRoot[path])) {
                        // File not found - redirect to virtual space

                        response.CacheControl = "public";
                        response.Expires = 31536000;
                        response.ExpiresAbsolute = DateTime.Now.AddYears(1);
                        response.Cache.SetCacheability(HttpCacheability.Public);
                        response.RedirectPermanent("/#!" + path, true);
                        return;
                    }

                    // Extract
                    using (var stream = new MemoryStream()) {
                        file.Extract(stream);
                        page = stream.ReadAllToByteArray();
                    }

                    // Add to cache
                    WebCache[path] = page;
                }
            }

            // Set cache headers
            if (path.Contains(".nocache.")) {
                response.CacheControl = "private";
                response.Expires = 0;
                response.ExpiresAbsolute = DateTime.Now;
                response.Cache.SetCacheability(HttpCacheability.NoCache);
            } else if (path.Contains(".cache.")) {
                response.CacheControl = "public";
                response.Expires = 365 * 24 * 60 * 60;
                response.ExpiresAbsolute = DateTime.Now.AddDays(365);
                response.Cache.SetCacheability(HttpCacheability.Public);
            } else {
                response.CacheControl = "private";
                response.Expires = 1 * 24 * 60 * 60;
                response.ExpiresAbsolute = DateTime.Now.AddDays(1);
                response.Cache.SetCacheability(HttpCacheability.Private);
            }

            // Set content type
            switch (Path.GetExtension(path).ToUpperInvariant()) {
                case ".JS":
                    response.ContentType = "text/javascript";
                    break;
                case ".JSON":
                    response.ContentType = "application/json";
                    break;
                case ".CSS":
                    response.ContentType = "text/css";
                    break;
                case ".JPG":
                case ".JPEG":
                    response.ContentType = "image/jpeg";
                    break;
                case ".PNG":
                    response.ContentType = "image/png";
                    break;
                case ".GIF":
                    response.ContentType = "image/gif";
                    break;
            }

            // Set compression
            response.Compress(request);

            // Write
            response.OutputStream.Write(page, 0, page.Length);
        }