Setting up redirect in web.config file

后端 未结 3 2184
别跟我提以往
别跟我提以往 2020-11-28 05:38

I\'m trying to redirect some unfriendly urls with more descriptive ones. These urls end in .aspx?cid=3916 with the last digits being different for each category

3条回答
  •  -上瘾入骨i
    2020-11-28 06:08

    In case that you need to add the http redirect in many sites, you could use it as a c# console program:

       class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
                return 1;
            }
    
            if (args.Length == 3)
            {
                if (args[0].ToLower() == "-insert-redirect")
                {
                    var path = args[1];
                    var value = args[2];
    
                    if (InsertRedirect(path, value))
                        Console.WriteLine("Redirect added.");
                    return 0;
                }
            }
    
            Console.WriteLine("Wrong parameters.");
            return 1;
    
        }
    
        static bool InsertRedirect(string path, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
    
                doc.Load(path);
    
                // This should find the appSettings node (should be only one):
                XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");
    
                var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
                if (existNode != null)
                    return false;
    
                // Create new  node
                XmlNode nodeNewKey = doc.CreateElement("httpRedirect");
    
                XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
                XmlAttribute attributeDestination = doc.CreateAttribute("destination");
                //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");
    
                // Assign values to both - the key and the value attributes:
    
                attributeEnable.Value = "true";
                attributeDestination.Value = value;
                //attributeResponseStatus.Value = "Permanent";
    
                // Add both attributes to the newly created node:
                nodeNewKey.Attributes.Append(attributeEnable);
                nodeNewKey.Attributes.Append(attributeDestination);
                //nodeNewKey.Attributes.Append(attributeResponseStatus);
    
                // Add the node under the 
                nodeAppSettings.AppendChild(nodeNewKey);
                doc.Save(path);
    
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception adding redirect: {e.Message}");
                return false;
            }
        }
    }
    

提交回复
热议问题