/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { if (node == null) { throw new ArgumentNullException("node"); } string to = node.GetRequiredAttribute(Constants.AttrTo, true); bool permanent = true; XmlNode permanentNode = node.Attributes.GetNamedItem(Constants.AttrPermanent); if (permanentNode != null) { if (!bool.TryParse(permanentNode.Value, out permanent)) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidBooleanAttribute, Constants.AttrPermanent), node); } } RedirectAction action = new RedirectAction(to, permanent); ParseConditions(node, action.Conditions, false, config); return(action); }
/// <summary> /// This method is called during the module's BeginRequest event. /// </summary> /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param> /// <param name="app">The HttpApplication instance.</param> protected override void Rewrite(string requestedPath, System.Web.HttpApplication app) { // get the configuration rules RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules; // iterate through each rule... for (int i = 0; i < rules.Count; i++) { // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory) string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$"; // Create a regex (note that IgnoreCase is set...) Regex re = new Regex(lookFor, RegexOptions.IgnoreCase); // See if a match is found if (re.IsMatch(requestedPath)) { // match found - do any replacement needed string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo)); // Rewrite the URL RewriterUtils.RewriteUrl(app.Context, sendToUrl); break; // exit the for loop } } }
private static void ReadActions(XmlNode node, IList actions, RewriterConfiguration config) { var childNode = node.FirstChild; while (childNode != null) { if (childNode.NodeType == XmlNodeType.Element) { var parsers = config.ActionParserFactory.GetParsers(childNode.LocalName); if (parsers != null) { var parsed = false; foreach (IRewriteActionParser parser in parsers) { var action = parser.Parse(childNode, config); if (action != null) { parsed = true; actions.Add(action); } } if (!parsed) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNotAllowed, node.FirstChild.Name), node); } } } childNode = childNode.NextSibling; } }
protected void SaveRule(object source, CommandEventArgs e) { //Get the index of the row to save int index = grdRules.EditItemIndex; RewriterRule rule = Rules[index]; var ctlMatch = (TextBox)grdRules.Items[index].Cells[2].FindControl("txtMatch"); var ctlReplace = (TextBox)grdRules.Items[index].Cells[2].FindControl("txtReplace"); if (!String.IsNullOrEmpty(ctlMatch.Text) && !String.IsNullOrEmpty(ctlReplace.Text)) { rule.LookFor = ctlMatch.Text; rule.SendTo = ctlReplace.Text; //Save the modified collection RewriterConfiguration.SaveConfig(Rules); } else { if (AddMode) { //Remove the temporary added row Rules.RemoveAt(Rules.Count - 1); AddMode = false; } } //Reset Edit Index grdRules.EditItemIndex = -1; BindRules(); }
public IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { XmlNode statusCodeNode = node.Attributes.GetNamedItem("status"); if (statusCodeNode == null) { return(null); } return(new MVCStatusAction((HttpStatusCode)Convert.ToInt32(statusCodeNode.Value))); }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { Response.Redirect(RewriterConfiguration.GetDefaultRule(DomainName)); } } catch { } }
/// <summary> /// Parses conditions from the node. /// </summary> /// <param name="node">The node.</param> /// <param name="conditions">Conditions list to add new conditions to.</param> /// <param name="negative">Whether the conditions should be negated.</param> /// <param name="config">Rewriter configuration</param> protected void ParseConditions(XmlNode node, IList conditions, bool negative, object config) { if (config == null) { return; } if (node == null) { throw new ArgumentNullException("node"); } if (conditions == null) { throw new ArgumentNullException("conditions"); } RewriterConfiguration rewriterConfig = config as RewriterConfiguration; // Parse attribute-based conditions. foreach (IRewriteConditionParser parser in rewriterConfig.ConditionParserPipeline) { IRewriteCondition condition = parser.Parse(node); if (condition != null) { if (negative) { condition = new NegativeCondition(condition); } conditions.Add(condition); } } // Now, process the nested <and> conditions. XmlNode childNode = node.FirstChild; while (childNode != null) { if (childNode.NodeType == XmlNodeType.Element) { if (childNode.LocalName == Constants.ElementAnd) { ParseConditions(childNode, conditions, negative, config); XmlNode childNode2 = childNode.NextSibling; node.RemoveChild(childNode); childNode = childNode2; continue; } } childNode = childNode.NextSibling; } }
public void Constructor_WithNullConfiguratonManager_Throws() { // Arrange XmlNode emptySection = CreateEmptyXmlNode(); IHttpContext httpContext = new MockHttpContext(); IConfigurationManager configurationManager = null; IRewriterConfiguration configuration = new RewriterConfiguration(new MockConfigurationManager(emptySection)); // Act/Assert ExceptionAssert.Throws <ArgumentNullException>(() => new RewriterEngine(httpContext, configurationManager, configuration)); }
/// <summary> /// Constructor. /// </summary> /// <param name="contextFacade">The context facade to use.</param> /// <param name="configuration">The configuration to use.</param> public RewriterEngine(IContextFacade contextFacade, RewriterConfiguration configuration) { if (contextFacade == null) { throw new ArgumentNullException("contextFacade"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } ContextFacade = contextFacade; _configuration = configuration; }
protected override object SaveViewState() { var config = new RewriterConfiguration(); config.Rules = Rules; object baseState = base.SaveViewState(); var allStates = new object[2]; allStates[0] = baseState; allStates[1] = XmlUtils.Serialize(config); return(allStates); }
/// ----------------------------------------------------------------------------- /// <summary> /// DeleteRule runs when a delete button is clicked /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 7/06/2006 Created /// </history> /// ----------------------------------------------------------------------------- private void DeleteRule(object source, DataGridCommandEventArgs e) { //Get the index of the row to delete int index = e.Item.ItemIndex; //Remove the rule from the rules collection Rules.RemoveAt(index); //Save the new collection RewriterConfiguration.SaveConfig(Rules); //Rebind the collection BindRules(); }
public void TestSave() { RewriterConfiguration configuration = RewriterConfigurationView.Instance.Configuration; RewriterRule rule = new RewriterRule(); rule.Lookfor = "123"; rule.Sendto = "456"; rule.Remark = "测试信息"; configuration.Rules.Add(rule); RewriterConfigurationView.Instance.Save(); }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { if (node == null) { throw new ArgumentNullException("node"); } if (config == null) { throw new ArgumentNullException("config"); } string cookieName = XmlNodeExtensions.GetRequiredAttribute(node, Constants.AttrCookie); string cookieValue = XmlNodeExtensions.GetRequiredAttribute(node, Constants.AttrValue, true); return(new SetCookieAction(cookieName, cookieValue)); }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { if (node == null) { throw new ArgumentNullException("node"); } if (config == null) { throw new ArgumentNullException("config"); } string headerName = node.GetRequiredAttribute(Constants.AttrHeader); string headerValue = node.GetRequiredAttribute(Constants.AttrValue, true); return(new AddHeaderAction(headerName, headerValue)); }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { if (node == null) { throw new ArgumentNullException("node"); } if (config == null) { throw new ArgumentNullException("config"); } string propertyName = node.GetRequiredAttribute(Constants.AttrProperty); string appSettingKey = node.GetRequiredAttribute(Constants.AttrKey); return(new SetAppSettingPropertyAction(propertyName, appSettingKey)); }
protected override void LoadViewState(object savedState) { object[] myState = (object[])savedState; if ((myState[0] != null)) { base.LoadViewState(myState[0]); } if ((myState[1] != null)) { RewriterConfiguration config = new RewriterConfiguration(); // Deserialize into RewriterConfiguration config = (RewriterConfiguration)XmlUtils.Deserialize(myState[1].ToString(), config.GetType()); Rules = config.Rules; } }
/// <summary> /// GetHandler is executed by the ASP.NET pipeline after the associated HttpModules have run. The job of /// GetHandler is to return an instance of an HttpHandler that can process the page. /// </summary> /// <param name="context">The HttpContext for this request.</param> /// <param name="requestType">The HTTP data transfer method (<b>GET</b> or <b>POST</b>)</param> /// <param name="url">The RawUrl of the requested resource.</param> /// <param name="pathTranslated">The physical path to the requested resource.</param> /// <returns>An instance that implements IHttpHandler; specifically, an HttpHandler instance returned /// by the <b>PageParser</b> class, which is the same class that the default ASP.NET PageHandlerFactory delegates /// to.</returns> public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { // log info to the Trace object... context.Trace.Write("RewriterFactoryHandler", "Entering RewriterFactoryHandler"); string sendToUrl = url; string filePath = pathTranslated; var config = RewriterConfiguration.GetConfig(); //ÅжÏconfigÅäÖÃÐÅÏ¢ if (config != null && config.Enabled) { // iterate through the rules foreach (RewriterRule rule in config.Rules) { // Get the pattern to look for (and resolve its URL) string lookFor = "^" + RewriterUtils.ResolveUrl(context.Request.ApplicationPath, rule.LookFor) + "$"; // Create a regular expression object that ignores case... Regex re = new Regex(lookFor, RegexOptions.IgnoreCase); // Check to see if we've found a match if (re.IsMatch(url)) { // do any replacement needed sendToUrl = RewriterUtils.ResolveUrl(context.Request.ApplicationPath, re.Replace(url, rule.SendTo)); // log info to the Trace object... context.Trace.Write("RewriterFactoryHandler", "Found match, rewriting to " + sendToUrl); // Rewrite the path, getting the querystring-less url and the physical file path string sendToUrlLessQString; RewriterUtils.RewriteUrl(context, sendToUrl, out sendToUrlLessQString, out filePath); // return a compiled version of the page context.Trace.Write("RewriterFactoryHandler", "Exiting RewriterFactoryHandler"); // log info to the Trace object... return(PageParser.GetCompiledPageInstance(sendToUrlLessQString, filePath, context)); } } } // if we reached this point, we didn't find a rewrite match context.Trace.Write("RewriterFactoryHandler", "Exiting RewriterFactoryHandler"); // log info to the Trace object... return(PageParser.GetCompiledPageInstance(url, filePath, context)); }
public void Rewrite_WithTemporarilyRedirectedUrl_RedirectsWithFound() { // <redirect url="^/Test3/(.+)$" to="/NewLocation/$1" permanent="false" /> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test3/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.Found, httpContext.StatusCode); Assert.AreEqual("/NewLocation/Page.aspx", httpContext.RedirectLocation); }
public void Rewrite_WithNotImplemented_Throws() { // <if url="^/Test17/(.+)$"> // <not-implemented /> // </if> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test17/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act/Assert HttpException httpEx = ExceptionAssert.Throws <HttpException>(() => engine.Rewrite()); Assert.AreEqual((int)HttpStatusCode.NotImplemented, httpEx.GetHttpCode()); }
public void Rewrite_WithRewrittenUrl_SetsLocation() { // <rewrite url="^/Test1/(.+)$" to="/NewLocation/$1" /> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test1/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.OK, httpContext.StatusCode); Assert.AreEqual("/NewLocation/Page.aspx", httpContext.RewrittenPath); }
public void Rewrite_WithSetProperty_SubstitutesPropertyValue() { // <set property="Property1" value="PropertyValue" /> // <rewrite url="^/Test4/(.+)$" to="/NewLocation/$1?Property1=${Property1}" /> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test4/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.OK, httpContext.StatusCode); Assert.AreEqual("/NewLocation/Page.aspx?Property1=PropertyValue", httpContext.RewrittenPath); }
public void Rewrite_WithRewrittenUrlAndContinue_AppliesNextRule() { // <rewrite url="^/Test6/(.+)" to="/NewLocation1/$1" processing="continue" /> // <rewrite url="^/NewLocation1/(.+)" to="/NewLocation2/$1" processing="stop" /> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test6/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.OK, httpContext.StatusCode); Assert.AreEqual("/NewLocation2/Page.aspx", httpContext.RewrittenPath); }
public void Rewrite_WithRewrittenUrlAndRestart_AppliesFirstRule() { // <rewrite url="^/Test7/(.+)" to="/Test1/$1" processing="restart" /> // (Should also apply the first rule in rewriter config on restart). // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test7/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.OK, httpContext.StatusCode); Assert.AreEqual("/NewLocation/Page.aspx", httpContext.RewrittenPath); }
protected override void LoadViewState(object savedState) { var myState = (object[])savedState; if ((myState[0] != null)) { base.LoadViewState(myState[0]); } if ((myState[1] != null)) { var config = new RewriterConfiguration(); //Deserialize into RewriterConfiguration var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(Convert.ToString(myState[1])); config = CBO.DeserializeObject <RewriterConfiguration>(xmlDocument); Rules = config.Rules; } }
public void Rewrite_WithAddHeader_AddsResponseHeader() { // <if url="^/Test18/(.+)$"> // <add header="Header1" value="HeaderValue" /> // </if> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test18/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert CollectionAssert.Contains(httpContext.ResponseHeaders.Keys, "Header1"); Assert.AreEqual("HeaderValue", httpContext.ResponseHeaders["Header1"]); }
protected override void LoadViewState(object savedState) { var myState = (object[])savedState; if ((myState[0] != null)) { base.LoadViewState(myState[0]); } if ((myState[1] != null)) { var config = new RewriterConfiguration(); //Deserialize into RewriterConfiguration #pragma warning disable 612,618 config = (RewriterConfiguration)XmlUtils.Deserialize(Convert.ToString(myState[1]), config.GetType()); #pragma warning restore 612,618 Rules = config.Rules; } }
public void Rewrite_WithExistsAndForbidden_SetsStatus() { // <if url="^/Test13/(.+)$" exists="README.txt"> // <set status="206" /> // </if> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test13/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.PartialContent, httpContext.StatusCode); Assert.IsNull(httpContext.RewrittenPath); Assert.IsNull(httpContext.RedirectLocation); }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { if (node == null) { throw new ArgumentNullException("node"); } if (config == null) { throw new ArgumentNullException("config"); } XmlNode statusCodeNode = node.Attributes.GetNamedItem(Constants.AttrStatus); if (statusCodeNode == null) { return(null); } return(new SetStatusAction((HttpStatusCode)Convert.ToInt32(statusCodeNode.Value))); }
public void Rewrite_WithPropertyMatchAndSetStatus_SetsStatus() { // <set property="Property3" value="PropertyValue" /> // <if url="^/Test12/(.+)$" property="Property3" match="^PropertyValue$"> // <set status="205" /> // </if> // Arrange MockHttpContext httpContext = new MockHttpContext("http://localhost/Test12/Page.aspx"); IConfigurationManager configurationManager = new ConfigurationManagerFacade(); IRewriterConfiguration configuration = new RewriterConfiguration(configurationManager); RewriterEngine engine = new RewriterEngine(httpContext, configurationManager, configuration); // Act engine.Rewrite(); // Assert Assert.AreEqual(HttpStatusCode.ResetContent, httpContext.StatusCode); // 205 Assert.IsNull(httpContext.RewrittenPath); Assert.IsNull(httpContext.RedirectLocation); }
/// <summary> /// This method is called during the module's BeginRequest event. /// </summary> /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param> /// <param name="app">The HttpApplication instance.</param> protected override void Rewrite(string requestedPath, System.Web.HttpApplication app) { // log information to the Trace object. app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter"); // get the configuration rules var config = RewriterConfiguration.GetConfig(); //ÅжÏconfigÅäÖÃÐÅÏ¢ if (config != null && config.Enabled) { // iterate through each rule... foreach (RewriterRule rule in config.Rules) { // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory) string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rule.LookFor) + "$"; // Create a regex (note that IgnoreCase is set...) Regex re = new Regex(lookFor, RegexOptions.IgnoreCase); // See if a match is found if (re.IsMatch(requestedPath)) { // match found - do any replacement needed string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rule.SendTo)); // log rewriting information to the Trace object app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl); // Rewrite the URL RewriterUtils.RewriteUrl(app.Context, sendToUrl); break; // exit the for loop } } } // Log information to the Trace object app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter"); }