ASP.NET: URI handling

后端 未结 6 2119
暗喜
暗喜 2021-01-06 05:53

I\'m writing a method which, let\'s say, given 1 and hello should return http://something.com/?something=1&hello=en.

I

6条回答
  •  盖世英雄少女心
    2021-01-06 06:35

    As far I know nothing here. So everybody has its own implementation.

    Example from LinqToTwitter.

        internal static string BuildQueryString(IEnumerable> parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
    
            StringBuilder builder = new StringBuilder();
            foreach (var pair in parameters.Where(p => !string.IsNullOrEmpty(p.Value)))
            {
                if (builder.Length > 0)
                {
                    builder.Append("&");
                }
    
                builder.Append(Uri.EscapeDataString(pair.Key));
                builder.Append("=");
                builder.Append(Uri.EscapeDataString(pair.Value));
            }
    
            return builder.ToString();
        }
    

    UPDATE:

    You can also create extension method:

    public static UriBuilder AddArgument(this UriBuilder builder, string key, string value)
    {
     #region Contract
    
     Contract.Requires(builder != null);
     Contract.Requires(key != null);
     Contract.Requires(value != null);
    
     #endregion
    
     var query = builder.Query;
    
     if (query.Length > 0)
     {
          query = query.Substring(1) + "&";
     } 
    
     query += Uri.EscapeDataString(key) + "="
          + Uri.EscapeDataString(value);
    
     builder.Query = query;
    
     return builder;
    }
    

    And usage:

    var b = new UriBuilder();
    b.AddArgument("test", "test");
    

    Please note that everything here is untested.

提交回复
热议问题