【问题标题】:.NET Submitting HTTP request to webservice that requires nameless parameter in query string.NET 向需要查询字符串中的无名参数的 Web 服务提交 HTTP 请求
【发布时间】:2013-06-09 18:26:16
【问题描述】:

我正在创建一些类来与 Web 服务(由第 3 方构建)进行交互,在(几乎)所有情况下都只接受 GET 查询。

我的一个类是 WebServiceClient 类,它封装了一个 System.Net.WebClient 类,我发现它非常有用,因为它允许您通过其 QueryString 属性添加名称=值对。我已经广泛使用了它。

不过,服务接受的其中一个请求类似于:

http://host:port/endpoint?C:/path/to/file/today.xml&Database=News&Destination=Server

现在,很明显,我习惯于查询字符串中的值是 name=value 的形式,但是在上面的示例中,第一个参数似乎没有名称。

有没有办法使用 WebClient 或不同的 .NET 类来复制它?

【问题讨论】:

    标签: .net web-services query-string webclient


    【解决方案1】:

    您可以拥有一个行为类似于 WebClient 的自定义子类,但会添加所需的怪异,如下所示: 需要重写 GetWebRequest 方法以考虑我们的新属性 NameLessParameter 以构建新的 Uri。

    public class SpecializedWebClient : WebClient
    {
        // set if you need Namelessvalue as 
        // your first QueryParam
        public string NameLessParameter { get; set; }
    
        protected override WebRequest GetWebRequest(Uri address)
        {
            var u = new UriBuilder(address);
            if (!String.IsNullOrEmpty(NameLessParameter))
            {
                string origQuery = String.Empty;
                if (!String.IsNullOrEmpty(u.Query))
                {
                    // strip off the first ? and add &
                    origQuery = "&" + u.Query.Substring(1);
                }
                u.Query = NameLessParameter + origQuery;
            }
            return base.GetWebRequest(u.Uri);
        }
    }
    

    用法

    var sc = new SpecializedWebClient();
    sc.QueryString.Add("foo", "42");
    sc.QueryString.Add("bar", "pi");
    sc.NameLessParameter=@"c:\bofh\removeuser.sh";
    string sdta = sc.DownloadString(@"http://www.example.com");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-22
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      相关资源
      最近更新 更多