예제 #1
0
        /// <summary>
        /// Rewrites the URL and redirect the request to destination page from rules in web.config
        /// </summary>
        public static void RewriteUrl()
        {
            RewriteConfigurationSection config = (RewriteConfigurationSection)ConfigurationManager.GetSection("rewrite");

            if (config != null)
            {
                if (config.Rules != null)
                {
                    foreach (RewriteRuleElement rule in config.Rules)
                    {
                        Regex r = new Regex(rule.Url, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                        Match m = r.Match(HttpContext.Current.Request.Url.AbsolutePath);
                        if (m.Success)
                        {
                            string destinationUrl = rule.Destination;

                            for (int i = 0; i < m.Groups.Count; i++)
                            {
                                if (m.Groups[i].Index > 0)
                                    destinationUrl = destinationUrl.Replace("$" + i.ToString(), m.Groups[i].Value);
                            }

                            RewriteContext ctx = new RewriteContext();
                            ctx.RewritedUrl = HttpContext.Current.Request.Url.AbsoluteUri;
                            HttpContext.Current.Items.Add("REWRITECONTEXT", ctx);
                            HttpContext.Current.RewritePath(destinationUrl + HttpContext.Current.Request.Url.Query);
                        }
                    }
                }
                else
                    throw new Exception("Cannot find <rules> node in web.config");
            }
            else
                throw new Exception("Cannot find <rewrite> node in web.config");
        }
		/// <summary>
		/// Determines if the condition is matched.
		/// </summary>
		/// <param name="context">The rewriting context.</param>
		/// <returns>True if the condition is met.</returns>
		public bool IsMatch(RewriteContext context)
		{
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (_regex == null)
			{
				lock (this)
				{
					if (_regex == null)
					{
						_regex = new Regex(context.ResolveLocation(Pattern), RegexOptions.IgnoreCase);
					}
				}
			}

			Match match = _regex.Match(context.Location);
			if (match.Success)
			{
				context.LastMatch = match;
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// Determines if the condition is matched.
		/// </summary>
		/// <param name="context">The rewriting context.</param>
		/// <returns>True if the condition is met.</returns>
		public override bool IsMatch(RewriteContext context)
		{
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            string property = context.Properties[PropertyName];
			if (property != null)
			{
				Match match = Pattern.Match(property);
				if (match.Success)
				{
					context.LastMatch = match;
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
예제 #4
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(RewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // Use double-checked locking pattern to synchronise access to the regex.
            if (_regex == null)
            {
                lock (this)
                {
                    if (_regex == null)
                    {
                        _regex = new Regex(context.ResolveLocation(Pattern), RegexOptions.IgnoreCase);
                    }
                }
            }

            Match match = _regex.Match(context.Location);
            if (match.Success)
            {
                context.LastMatch = match;
            }

            return match.Success;
        }
예제 #5
0
 /// <summary>
 /// Determines if the condition is matched.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 /// <returns>True if the condition is met.</returns>
 public bool IsMatch(RewriteContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     return !_chainedCondition.IsMatch(context);
 }
예제 #6
0
 /// <summary>
 /// Determines if the condition is matched.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 /// <returns>True if the condition is met.</returns>
 public override bool IsMatch(RewriteContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     return Pattern.IsMatch(context.Method);
 }
		/// <summary>
		/// Executes the action.
		/// </summary>
		/// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(RewriteContext context)
		{
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            context.Headers.Add(Header, Value);
            return RewriteProcessing.ContinueProcessing;
		}
 /// <summary>
 ///     Executes the action.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 public virtual RewriteProcessing Execute(RewriteContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     context.Location = context.ResolveLocation(context.Expand(Location));
     return RewriteProcessing.StopProcessing;
 }
예제 #9
0
 /// <summary>
 /// Determines if the condition is matched.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 /// <returns>True if the condition is met.</returns>
 public bool IsMatch(RewriteContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     string ipAddress = context.Properties[Constants.RemoteAddressHeader];
     return (ipAddress != null && _range.InRange(IPAddress.Parse(ipAddress)));
 }
		/// <summary>
		/// Determines if the condition is matched.
		/// </summary>
		/// <param name="context">The rewriting context.</param>
		/// <returns>True if the condition is met.</returns>
		public bool IsMatch(RewriteContext context)
		{
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            string filename = context.MapPath(context.Expand(_location));
			return File.Exists(filename) || Directory.Exists(filename);
		}
예제 #11
0
 /// <summary>
 /// Executes the action.
 /// </summary>
 /// <param name="context">The rewrite context.</param>
 public RewriteProcessing Execute(RewriteContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     context.Properties.Set(Name, context.Expand(Value));
     return RewriteProcessing.ContinueProcessing;
 }
		/// <summary>
		/// Executes the action.
		/// </summary>
		/// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(RewriteContext context)
		{
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpCookie cookie = new HttpCookie(Name, Value);
			context.Cookies.Add(cookie);
            return RewriteProcessing.ContinueProcessing;
		}
예제 #13
0
 /// <summary>
 ///     Executes the action.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 public virtual RewriteProcessing Execute(RewriteContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     context.StatusCode = StatusCode;
     return ((int) StatusCode >= 300)
                ? RewriteProcessing.StopProcessing
                : RewriteProcessing.ContinueProcessing;
 }
예제 #14
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(RewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // If the value cannot be found in AppSettings, default to an empty string.
            string appSettingValue = context.ConfigurationManager.AppSettings[_appSettingsKey] ?? String.Empty;
            context.Properties.Set(Name, appSettingValue);
            return RewriteProcessing.ContinueProcessing;
        }
예제 #15
0
        /// <summary>
        ///     Determines if the rewrite rule matches.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool IsMatch(RewriteContext context)
        {
            // Ensure the conditions are met.
            foreach (IRewriteCondition condition in Conditions)
            {
                if (!condition.IsMatch(context))
                {
                    return false;
                }
            }

            return true;
        }
예제 #16
0
        /// <summary>
        ///     Executes the action.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        public override RewriteProcessing Execute(RewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            base.Execute(context);

            context.StatusCode = (_permanent)
                                     ? HttpStatusCode.Moved
                                     : HttpStatusCode.Found;

            return RewriteProcessing.StopProcessing;
        }
예제 #17
0
        /// <summary>
        /// Executes the rule.
        /// </summary>
        /// <param name="context">The rewrite context</param>
        public virtual RewriteProcessing Execute(RewriteContext context)
        {
            // Execute the actions.
            for (int i = 0; i < Actions.Count; i++)
            {
                IRewriteCondition condition = Actions[i] as IRewriteCondition;
                if (condition == null || condition.IsMatch(context))
                {
                    IRewriteAction action = Actions[i];
                    RewriteProcessing processing = action.Execute(context);
                    if (processing != RewriteProcessing.ContinueProcessing)
                    {
                        return processing;
                    }
                }
            }

            return RewriteProcessing.ContinueProcessing;
        }
예제 #18
0
        /// <summary>
        /// Determines if the condition is matched.
        /// </summary>
        /// <param name="context">The rewriting context.</param>
        /// <returns>True if the condition is met.</returns>
        public bool IsMatch(RewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            try
            {
                string filename = context.MapPath(context.Expand(_location));
                return File.Exists(filename) || Directory.Exists(filename);
            }
            catch
            {
                // An HTTP exception or an I/O exception indicates that the file definitely
                // does not exist.
                return false;
            }
        }
예제 #19
0
        public void ModifiesHostThatDoesntMatch()
        {
            //Arrange
            RewriteContext context = new RewriteContext();

            context.Result = RuleResult.ContinueRules;
            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Scheme      = "https";
            httpContext.Request.Host        = new HostString("www2.foo.bar");
            httpContext.Request.PathBase    = null;
            httpContext.Request.Path        = new PathString("/primary/secondary");
            httpContext.Request.QueryString = new QueryString("?Foo=Bar");

            context.HttpContext = httpContext;

            //Act
            rule.ApplyRule(context);

            //Assert
            Assert.AreEqual("https://www.foo.bar/primary/secondary?Foo=Bar", context.HttpContext.Response.Headers[HeaderNames.Location].ToString());
            Assert.AreEqual((int)HttpStatusCode.MovedPermanently, context.HttpContext.Response.StatusCode);
            Assert.AreEqual(RuleResult.EndResponse, context.Result);
        }
        public virtual void ApplyRule(RewriteContext context)
        {
            var request  = context.HttpContext.Request;
            var path     = request.Path.ToString().Trim();
            var response = context.HttpContext.Response;

            if (string.IsNullOrEmpty(path) || path == "/")
            {
                string redirectUrl = "https://madpay724.ir";
                response.Headers[HeaderNames.Location] = redirectUrl;
                response.StatusCode = StatusCodes.Status301MovedPermanently;
                context.Result      = RuleResult.EndResponse;
            }
            else
            {
                if (request.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
                {
                    string redirectUrl = $"{request.Scheme}://{request.Host.Value.Replace("www.", "")}{request.Path}{request.QueryString}";
                    response.Headers[HeaderNames.Location] = redirectUrl;
                    response.StatusCode = StatusCodes.Status301MovedPermanently;
                    context.Result      = RuleResult.EndResponse;
                }
            }
        }
예제 #21
0
    public override MatchResults Evaluate(string input, RewriteContext context)
    {
        switch (_operation)
        {
        case StringOperationType.Equal:
            return(string.Compare(input, _value, _stringComparison) == 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure);

        case StringOperationType.Greater:
            return(string.Compare(input, _value, _stringComparison) > 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure);

        case StringOperationType.GreaterEqual:
            return(string.Compare(input, _value, _stringComparison) >= 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure);

        case StringOperationType.Less:
            return(string.Compare(input, _value, _stringComparison) < 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure);

        case StringOperationType.LessEqual:
            return(string.Compare(input, _value, _stringComparison) <= 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure);

        default:
            Debug.Fail("This is never reached.");
            throw new InvalidOperationException();     // Will never be thrown
        }
    }
예제 #22
0
        void IRule.ApplyRule(RewriteContext context)
        {
            var  request   = context.HttpContext.Request;
            bool wasSecure = Rewrite(request);

            if (!wasSecure && _httpsPolicy == HttpsPolicy.Required)
            {
                // Redirect to https.
                var newUrl = string.Concat(
                    "https://",
                    request.Host.ToUriComponent(),
                    request.PathBase.ToUriComponent(),
                    request.Path.ToUriComponent(),
                    request.QueryString.ToUriComponent());
                var action = new RedirectResult(newUrl);
                // Execute the redirect.
                ActionContext actionContext = new ActionContext()
                {
                    HttpContext = context.HttpContext
                };
                action.ExecuteResult(actionContext);
                context.Result = RuleResult.EndResponse;
            }
        }
예제 #23
0
        public void ApplyRule_TrackAllCaptures()
        {
            var xml   = new StringReader(@"<rewrite>
                <rules>
                <rule name=""Test"">
                <match url = ""(.*)"" ignoreCase=""false"" />
                <conditions trackAllCaptures = ""true"" >
                <add input = ""{REQUEST_URI}"" pattern = ""^/([a-zA-Z]+)/([0-9]+)/$"" />
                </conditions >
                <action type = ""None""/>
                </rule>
                </rules>
                </rewrite>");
            var rules = new UrlRewriteFileParser().Parse(xml, false);

            Assert.Equal(1, rules.Count);
            Assert.True(rules[0].Conditions.TrackAllCaptures);
            var context = new RewriteContext {
                HttpContext = new DefaultHttpContext()
            };

            rules.FirstOrDefault().ApplyRule(context);
            Assert.Equal(RuleResult.ContinueRules, context.Result);
        }
예제 #24
0
        /// <summary>Redirect to `index.php` if the the file does not exist.</summary>
        static void ShortUrlRule(RewriteContext context, IFileProvider files)
        {
            var req     = context.HttpContext.Request;
            var subpath = req.Path.Value;

            if (subpath != "/" && subpath.Length != 0)
            {
                if (subpath.IndexOf("wp-content/", StringComparison.Ordinal) != -1 || // it is in the wp-content -> definitely a file
                    files.GetFileInfo(subpath).Exists ||                              // the script is in the file system
                    Context.TryGetDeclaredScript(subpath.Substring(1)).IsValid ||     // the script is declared (compiled) in Context but not in the file system
                    context.StaticFileProvider.GetFileInfo(subpath).Exists ||         // the script is in the file system
                    subpath == "/favicon.ico")                                        // 404 // even the favicon is not there, let the request proceed
                {
                    // proceed to Static Files
                    return;
                }

                if (files.GetDirectoryContents(subpath).Exists)
                {
                    var lastchar = subpath[subpath.Length - 1];
                    if (lastchar != '/' && lastchar != '\\')
                    {
                        // redirect to the directory with leading slash:
                        context.HttpContext.Response.Redirect(req.PathBase + subpath + "/" + req.QueryString, true);
                        context.Result = RuleResult.EndResponse;
                    }

                    // proceed to default document
                    return;
                }
            }

            // everything else is handled by `index.php`
            req.Path       = new PathString("/index.php");
            context.Result = RuleResult.SkipRemainingRules;
        }
예제 #25
0
        public virtual void ApplyRule(RewriteContext context)
        {
            var req = context.HttpContext.Request;

            if (req.Host.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase))
            {
                context.Result = RuleResult.ContinueRules;
                return;
            }

            if (!req.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
            {
                context.Result = RuleResult.ContinueRules;
                return;
            }

            var wwwHost  = new HostString($"{req.Host.Value.Replace("www.", string.Empty)}");
            var newUrl   = UriHelper.BuildAbsolute(req.Scheme, wwwHost, req.PathBase, req.Path, req.QueryString);
            var response = context.HttpContext.Response;

            response.StatusCode = 301;
            response.Headers[HeaderNames.Location] = newUrl;
            context.Result = RuleResult.EndResponse;
        }
예제 #26
0
        public void ApplyRule(RewriteContext context)
        {
            var req         = context.HttpContext.Request;
            var currentHost = req.Host;

            if (currentHost.Host.StartsWith("www."))
            {
                var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 443);
                var newUrl  = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
                context.HttpContext.Response.Redirect(newUrl.ToString(), false);
                context.Result = RuleResult.EndResponse;
            }
            else
            {
                if (req.Scheme == "http")
                {
                    var newUrl = $"http://www.{currentHost.Host}{req.PathBase}{req.Path}{req.QueryString}";
                    //new StringBuilder()
                    //.Append("https://")
                    //.Append("www.")
                    //.Append(new HostString(currentHost.Host))
                    //.Append(req.PathBase)
                    //.Append(req.Path)
                    //.Append(req.QueryString);
                    context.HttpContext.Response.Redirect(newUrl.ToString(), false);
                    context.Result = RuleResult.EndResponse;
                }
            }
            //else
            //{
            //    var newHost = new HostString(currentHost.Host, currentHost.Port ?? 443);
            //    var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
            //    context.HttpContext.Response.Redirect(newUrl.ToString(), false);
            //    context.Result = RuleResult.EndResponse;
            //}
        }
예제 #27
0
        public void ApplyRule_WithCanonicalUrl_DoNothing(
            bool appendTrailingSlash,
            bool lowercaseUrls,
#pragma warning disable CA1054 // Uri parameters should not be strings
            string url)
#pragma warning restore CA1054 // Uri parameters should not be strings
        {
            var rule    = new RedirectToCanonicalUrlRule(appendTrailingSlash, lowercaseUrls);
            var context = new RewriteContext()
            {
                HttpContext = new DefaultHttpContext(),
            };

            context.HttpContext.SetEndpoint(new Endpoint(x => Task.CompletedTask, new EndpointMetadataCollection(), "Name"));
            var request = context.HttpContext.Request;

            request.Method = HttpMethods.Get;
            SetUrl(url, request);

            rule.ApplyRule(context);

            Assert.Equal(RuleResult.ContinueRules, context.Result);
            Assert.Equal(StatusCodes.Status200OK, context.HttpContext.Response.StatusCode);
        }
예제 #28
0
        public void DoesNotModifyMatchingHost()
        {
            //Arrange
            RewriteContext context = new RewriteContext();

            context.Result = RuleResult.ContinueRules;
            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Scheme      = "https";
            httpContext.Request.Host        = new HostString(urlConfig.CanonicalHost);
            httpContext.Request.PathBase    = null;
            httpContext.Request.Path        = new PathString("/primary/secondary");
            httpContext.Request.QueryString = new QueryString("?Foo=Bar");

            context.HttpContext = httpContext;

            //Act
            rule.ApplyRule(context);

            //Assert
            Assert.AreEqual(string.Empty, context.HttpContext.Response.Headers[HeaderNames.Location].ToString());
            Assert.AreEqual((int)HttpStatusCode.OK, context.HttpContext.Response.StatusCode);
            Assert.AreEqual(RuleResult.ContinueRules, context.Result);
        }
예제 #29
0
 public abstract string Evaluate(RewriteContext context, BackReferenceCollection ruleBackReferences, BackReferenceCollection conditionBackReferences);
예제 #30
0
    public virtual void ApplyRule(RewriteContext context)
    {
        var request  = context.HttpContext.Request;
        var path     = request.Path;
        var pathBase = request.PathBase;

        Match initMatchResults;

        if (!path.HasValue)
        {
            initMatchResults = InitialMatch.Match(string.Empty);
        }
        else
        {
            initMatchResults = InitialMatch.Match(path.ToString().Substring(1));
        }


        if (initMatchResults.Success)
        {
            var newPath  = initMatchResults.Result(Replacement);
            var response = context.HttpContext.Response;

            response.StatusCode = StatusCode;
            context.Result      = RuleResult.EndResponse;

            string encodedPath;

            if (string.IsNullOrEmpty(newPath))
            {
                encodedPath = pathBase.HasValue ? pathBase.Value : "/";
            }
            else
            {
                var host        = default(HostString);
                var schemeSplit = newPath.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal);
                if (schemeSplit >= 0)
                {
                    schemeSplit += Uri.SchemeDelimiter.Length;
                    var pathSplit = newPath.IndexOf('/', schemeSplit);

                    if (pathSplit == -1)
                    {
                        host    = new HostString(newPath.Substring(schemeSplit));
                        newPath = "/";
                    }
                    else
                    {
                        host    = new HostString(newPath.Substring(schemeSplit, pathSplit - schemeSplit));
                        newPath = newPath.Substring(pathSplit);
                    }
                }

                if (newPath[0] != '/')
                {
                    newPath = '/' + newPath;
                }

                var resolvedQuery = request.QueryString;
                var resolvedPath  = newPath;
                var querySplit    = newPath.IndexOf('?');
                if (querySplit >= 0)
                {
                    resolvedQuery = request.QueryString.Add(QueryString.FromUriComponent(newPath.Substring(querySplit)));
                    resolvedPath  = newPath.Substring(0, querySplit);
                }

                encodedPath = host.HasValue
                    ? UriHelper.BuildAbsolute(request.Scheme, host, pathBase, resolvedPath, resolvedQuery, default)
                    : UriHelper.BuildRelative(pathBase, resolvedPath, resolvedQuery, default);
            }

            // not using the HttpContext.Response.redirect here because status codes may be 301, 302, 307, 308
            response.Headers.Location = encodedPath;

            context.Logger.RedirectedRequest(newPath);
        }
    }
예제 #31
0
 /// <summary>
 ///     Determines if the condition is matched.
 /// </summary>
 /// <param name="context">The rewriting context.</param>
 /// <returns>True if the condition is met.</returns>
 public abstract bool IsMatch(RewriteContext context);
예제 #32
0
 public override string?Evaluate(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
 {
     return(_literal);
 }
        public void Execute(RewriteContext context)
        {
            Context = context;

            Run();
        }
예제 #34
0
 public override string?Evaluate(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
 {
     return(context.HttpContext.Request.Path);
 }
예제 #35
0
        public override string Evaluate(RewriteContext context, BackReferenceCollection ruleBackReferences, BackReferenceCollection conditionBackReferences)
        {
            var key = _pattern.Evaluate(context, ruleBackReferences, conditionBackReferences).ToLowerInvariant();

            return(_rewriteMap[key]);
        }
 public override string Evaluate(RewriteContext context, BackReferenceCollection ruleBackReferences, BackReferenceCollection conditionBackReferences)
 {
     return(context.HttpContext.Features.Get <IHttpRequestFeature>()?.Protocol);
 }
예제 #37
0
        public override void ApplyAction(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
        {
            var pattern = Url !.Evaluate(context, ruleBackReferences, conditionBackReferences);
            var request = context.HttpContext.Request;

            if (string.IsNullOrEmpty(pattern))
            {
                pattern = "/";
            }

            if (EscapeBackReferences)
            {
                // because escapebackreferences will be encapsulated by the pattern, just escape the pattern
                pattern = Uri.EscapeDataString(pattern);
            }


            // TODO PERF, substrings, object creation, etc.
            if (pattern.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal) >= 0)
            {
                string         scheme;
                HostString     host;
                PathString     path;
                QueryString    query;
                FragmentString fragment;
                UriHelper.FromAbsolute(pattern, out scheme, out host, out path, out query, out fragment);

                if (query.HasValue)
                {
                    if (QueryStringAppend)
                    {
                        request.QueryString = request.QueryString.Add(query);
                    }
                    else
                    {
                        request.QueryString = query;
                    }
                }
                else if (QueryStringDelete)
                {
                    request.QueryString = QueryString.Empty;
                }

                request.Scheme = scheme;
                request.Host   = host;
                request.Path   = path;
            }
            else
            {
                var split = pattern.IndexOf('?');
                if (split >= 0)
                {
                    var path = pattern.Substring(0, split);
                    if (path[0] == '/')
                    {
                        request.Path = PathString.FromUriComponent(path);
                    }
                    else
                    {
                        request.Path = PathString.FromUriComponent('/' + path);
                    }

                    if (QueryStringAppend)
                    {
                        request.QueryString = request.QueryString.Add(
                            QueryString.FromUriComponent(
                                pattern.Substring(split)));
                    }
                    else
                    {
                        request.QueryString = QueryString.FromUriComponent(
                            pattern.Substring(split));
                    }
                }
                else
                {
                    if (pattern[0] == '/')
                    {
                        request.Path = PathString.FromUriComponent(pattern);
                    }
                    else
                    {
                        request.Path = PathString.FromUriComponent('/' + pattern);
                    }

                    if (QueryStringDelete)
                    {
                        request.QueryString = QueryString.Empty;
                    }
                }
            }
            context.Result = Result;
        }
예제 #38
0
 public static MatchResults Evaluate(IEnumerable <Condition> conditions, RewriteContext context, BackReferenceCollection backReferences)
 {
     return(Evaluate(conditions, context, backReferences, trackAllCaptures: false));
 }
예제 #39
0
        public override MatchResults Evaluate(string input, RewriteContext context)
        {
            var fileInfo = context.StaticFileProvider.GetFileInfo(input);

            return(fileInfo.Exists && fileInfo.Length > 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure);
        }
예제 #40
0
        public IDisposable RewritePath(string newVirtualPath, bool rebaseClientPath)
        {
            IDisposable ctx = new RewriteContext(CurrentVirtualPathAndQuery, false, this);

            int index = newVirtualPath.IndexOf('?');
            if (index >= 0)
            {
                 string newQueryString = (index < (newVirtualPath.Length - 1)) ? newVirtualPath.Substring(index + 1) : string.Empty;
                _query = new HttpValueCollection(newQueryString);
                newVirtualPath = newVirtualPath.Substring(0, index);
            }

            _currentVirtualFilePath = newVirtualPath;

            return ctx;
        }
예제 #41
0
        private string GetURL(RewriteContext context)
        {
            var request = context.HttpContext.Request;

            return($"{request.Scheme}://{request.Host.Value}{request.PathBase}{request.Path}");
        }
예제 #42
0
        public override void ApplyAction(RewriteContext context, BackReferenceCollection ruleBackReferences, BackReferenceCollection conditionBackReferences)
        {
            var options = GetOrCreateOptions();

            context.HttpContext.Response.Cookies.Append(Name, Value ?? string.Empty, options);
        }
예제 #43
0
    public virtual void ApplyRule(RewriteContext context)
    {
        var   path = context.HttpContext.Request.Path;
        Match initMatchResults;

        if (path == PathString.Empty)
        {
            initMatchResults = InitialMatch.Match(path.ToString());
        }
        else
        {
            initMatchResults = InitialMatch.Match(path.ToString().Substring(1));
        }

        if (initMatchResults.Success)
        {
            var result  = initMatchResults.Result(Replacement);
            var request = context.HttpContext.Request;

            if (StopProcessing)
            {
                context.Result = RuleResult.SkipRemainingRules;
            }

            if (string.IsNullOrEmpty(result))
            {
                result = "/";
            }

            if (result.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal) >= 0)
            {
                string      scheme;
                HostString  host;
                PathString  pathString;
                QueryString query;
                UriHelper.FromAbsolute(result, out scheme, out host, out pathString, out query, out _);

                request.Scheme      = scheme;
                request.Host        = host;
                request.Path        = pathString;
                request.QueryString = query.Add(request.QueryString);
            }
            else
            {
                var split = result.IndexOf('?');
                if (split >= 0)
                {
                    var newPath = result.Substring(0, split);
                    if (newPath[0] == '/')
                    {
                        request.Path = PathString.FromUriComponent(newPath);
                    }
                    else
                    {
                        request.Path = PathString.FromUriComponent('/' + newPath);
                    }
                    request.QueryString = request.QueryString.Add(
                        QueryString.FromUriComponent(
                            result.Substring(split)));
                }
                else
                {
                    if (result[0] == '/')
                    {
                        request.Path = PathString.FromUriComponent(result);
                    }
                    else
                    {
                        request.Path = PathString.FromUriComponent('/' + result);
                    }
                }
            }

            context.Logger.RewrittenRequest(result);
        }
    }
예제 #44
0
 public override string?Evaluate(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
 {
     return(context.HttpContext.GetServerVariable(_variableName) ?? _fallbackThunk().Evaluate(context, ruleBackReferences, conditionBackReferences));
 }
예제 #45
0
        private string GetURL(RewriteContext context)
        {
            var request = context.HttpContext.Request;

            return(WebUtility.UrlDecode($"{request.Scheme}://{request.Host.Value}{request.PathBase}{request.Path}{request.QueryString}"));
        }
예제 #46
0
 // Explicitly say that nothing happens
 public override void ApplyAction(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
 {
     context.Result = Result;
 }
예제 #47
0
 public override string?Evaluate(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
 {
     return(context.HttpContext.Connection.RemoteIpAddress?.ToString());
 }
        public void Execute(RewriteContext context)
        {
            Context = context;

            Run();
        }
예제 #49
0
 public override string Evaluate(RewriteContext context, BackReferenceCollection ruleBackReferences, BackReferenceCollection conditionBackReferences)
 {
     return(context.HttpContext.Connection.RemotePort.ToString(CultureInfo.InvariantCulture));
 }
예제 #50
0
 public override string?Evaluate(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
 {
     return(_uriMatchPart == UriMatchPart.Full ? context.HttpContext.Request.GetEncodedUrl() : (string)context.HttpContext.Request.Path);
 }
예제 #51
0
 /// <summary>
 ///     Executes the action.
 /// </summary>
 /// <param name="context">The rewrite context.</param>
 public override RewriteProcessing Execute(RewriteContext context)
 {
     base.Execute(context);
     return _processing;
 }
예제 #52
0
        public override MatchResults Evaluate(string pattern, RewriteContext context)
        {
            var res = context.StaticFileProvider.GetFileInfo(pattern).IsDirectory;

            return(new MatchResults(success: res != Negate));
        }