开发者

Is there an UriAgilityPack / UrlAgilityPack?

开发者 https://www.devze.com 2023-03-01 15:25 出处:网络
I\'m always trying to figure out some url/uri methodology with asp.net to manipulate a uri/url. It\'d be nice to have:

I'm always trying to figure out some url/uri methodology with asp.net to manipulate a uri/url.

It'd be nice to have:

UriAgilityPack uri = new UriAgilityPack("http://some.com/path?query1=value1");

or

UriAgilityPack uri = new UriAgilityPack().LoadSiteRelative("~/path?query1=value1");

Then with

enum Schemes {
  Http,
  Https
}

uri.Scheme = Schemes.Https;

and/or

foreach(QueryItem item in uri.Query)
   // do something with item

and/or

uri.Query.Add("AddToCart", 5)

string s = uri.ToString() // https://some.com/path?query1=value1&AddToCart=5

or

string root = uri.RootPath                // /开发者_如何学Gopath?query1=value1&AddToCart=5
string relative = uri.RootRelativePath;   // ~/path?query1=value1&AddToCart=5


No need for an agility pack for something that's already built into the framework. So start with an Uri:

var uri = new Uri("http://some.com/path?query1=value1");

and then:

Console.WriteLine(uri.Scheme);

and then:

var nvc = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in nvc)
{
    Console.WriteLine("key: {0}, value: {1}", key, nvc[key]);
}

and then:

var builder = new UriBuilder(uri);
var nvc = HttpUtility.ParseQueryString(uri.Query);
nvc.Add("AddToCart", "5");
builder.Query = nvc.ToString();
Console.WriteLine(builder.ToString());

and finally:

Console.WriteLine(builder.Uri.PathAndQuery);

See how easy it is? And what's even cooler is that you can do this in a desktop application, you don't need ASP.NET at all.

If I had one advice to give you when dealing with urls in .NET it would be to never use string concatenations. Always use the API as it will guarantee you proper encoding and respect of web standards.

0

精彩评论

暂无评论...
验证码 换一张
取 消