/// <summary> /// 创建新的uri /// </summary> /// <param name="uri">原始uri</param> /// <param name="keyValues">键值对</param> /// <returns></returns> protected virtual Uri CreateUri(Uri uri, IEnumerable <KeyValue> keyValues) { var uriValue = new UriValue(uri); foreach (var keyValue in keyValues) { uriValue = uriValue.Replace(keyValue.Key, keyValue.Value, out var replaced); if (replaced == false) { uriValue = uriValue.AddQuery(keyValue.Key, keyValue.Value); } } return(uriValue.ToUri()); }
public void AddQueryTest() { var uriValue = new UriValue("http://www.webapiclient.com"); uriValue = uriValue.AddQuery("a", "a"); Assert.Equal("http://www.webapiclient.com/?a=a", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path"); uriValue = uriValue.AddQuery("a", "a"); Assert.Equal("http://www.webapiclient.com/path?a=a", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path/"); uriValue = uriValue.AddQuery("a", "a"); Assert.Equal("http://www.webapiclient.com/path/?a=a", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path/?"); uriValue = uriValue.AddQuery("a", "a"); Assert.Equal("http://www.webapiclient.com/path/?a=a", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path?x=1"); uriValue = uriValue.AddQuery("a", "a"); Assert.Equal("http://www.webapiclient.com/path?x=1&a=a", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path?x=1&"); uriValue = uriValue.AddQuery("a", "a"); Assert.Equal("http://www.webapiclient.com/path?x=1&a=a", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path?x=1&"); uriValue = uriValue.AddQuery("a", "我"); Assert.Equal($"http://www.webapiclient.com/path?x=1&a={Uri.EscapeDataString("我")}", uriValue.ToString()); uriValue = new UriValue("http://www.webapiclient.com/path/?x=1&"); uriValue = uriValue.AddQuery("a", "我"); Assert.True(uriValue.ToString() == $"http://www.webapiclient.com/path/?x=1&a={Uri.EscapeDataString("我")}"); }