asp.net – 是否有支持请求参数连接的URL构建器?

前端之家收集整理的这篇文章主要介绍了asp.net – 是否有支持请求参数连接的URL构建器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望实现以下内容
UrlBuilder ub = new UrlBuilder("http://www.google.com/search");
ub.Parameters.Add("q","request");
ub.Parameters.Add("sourceid","ie8");

string uri = ub.ToString(); //http://www.google.com/search?q=request&sourceid=ie8

.NET中有什么东西,或者我必须创建自己的东西吗?

解决方法

我所知道的并不存在.这里有一些简单的东西可以满足您的需求.用法是:
UrlBuilder ub = new UrlBuilder("www.google.com/search")
        .AddQuery("q","request")
        .AddQuery("sourceid","ie8");

        string url=ub.ToString();

==

代码是:

public class UrlBuilder
    {
        private string _authority;
        private string _host;
        private int? _port;
        private Dictionary<string,object> _query = new Dictionary<string,object>();

        public UrlBuilder(string host)
            : this("http",host,null)
        {

        }
        public UrlBuilder(string authority,string host)
            : this(authority,null)
        {
        }
        public UrlBuilder(string authority,string host,int? port)
        {
            this._authority = authority;
            this._host = host;
            this._port = port;
        }

        public UrlBuilder AddQuery(string key,object value)
        {
            this._query.Add(key,value);
            return this;
        }

        public override string ToString()
        {
            string url = _authority + "://" + _host;
            if (_port.HasValue)
            {
                url += ":" + _port.ToString();
            }


            return AppendQuery(url);
        }

        private string AppendQuery(string url)
        {
            if (_query.Count == 0)
            {
                return url;
            }

            url += "?";
            bool isNotFirst = false;
            foreach (var key in this._query.Keys)
            {
                if (isNotFirst)
                {
                    url += "&";
                }
                url += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(this._query[key].ToString());
                isNotFirst = true;
            }

            return url;
        }
    }
}
原文链接:https://www.f2er.com/aspnet/248739.html

猜你在找的asp.Net相关文章