Monday, November 22, 2010

Разбор URL

Для разбора URL на части использовать методы Replace, IndexOf и т.д. - не правильный подход. Например, удаление префикса:

url.Replace("http://", "") // так не правильно!

Почему? Как минимум, это не будет работать на https-протоколе.

Правильный путь - использовать класс UriBuilder:

namespace UriParse
{
      class Class1
      {
            [STAThread]
            static void Main(string[] args)
            {

                  UriBuilder parser = new UriBuilder("http://microsoft.com:80/default.aspx?id=55");
                  Console.WriteLine(parser.Host);    // microsoft.com
                  Console.WriteLine(parser.Scheme);  // http
                  Console.WriteLine(parser.Uri);     //
http://microsoft.com/default.aspx?id=55
                  Console.WriteLine(parser.Path);    // /default.aspx
                  Console.WriteLine(parser.Port);    // 80
                  Console.WriteLine(parser.Query);   // ?id=55
            }
      }
}

No comments: