2015-11-03 170 views
0

我有一个webclient,我想与多个供应商连接。为WebClient设置自定义标头

除了uri和数据之外,还有头文件需要考虑,因为它们可能因供应商不同而不同。围绕客户端,我有很多其他的东西 - 所以我想写这个代码一次。

所以,我试图创建一个基本方法,它具有所有主要功能 - 类似下面的例子 - 这将允许我填写调用函数的空白。

public string Post() 
    { 
     try 
     { 
      var client = new CustomWebClient(); 

      return client.UploadString("", ""); 
     } 
     catch (WebException ex) 
     { 
      switch (ex.Status) 
      { 
       case WebExceptionStatus.Timeout: 
        break; 
       default: 
        break; 
      } 

      throw new Exception(); 
     } 
     catch (Exception ex) 
     { 
      throw new Exception(); 
     } 
     finally 
     { 
      client.Dispose(); 
     } 
    } 

显然很容易在地址和数据作为参数传递,但我怎么可以设置使用client.Headers.Add()什么标题?

我正在努力想出一个模式,工作,没有气味。

+0

你可以'client.Headers.Add(“test”,“test”);' –

回答

2

由于Post()方法是CustomWebClient的公共方法,因此通过属性设置器或构造函数初始化为方法后置设置所有必需的属性将是一个很好的设计。

public class CustomWebClient 
{ 
    public NameValueCollection Headers 
    { 
     get; 
     set; 
    } 

    public CustomWebClient() 
    { 
     this.Headers = new NameValueCollection(); 
    } 

    //Overload the constructor based on your requirement. 

    public string Post() 
    { 
     //Perform the post or UploadString with custom logic 
    }  

    //Overload the method Post for passing various parameters like the Url(if required) 
} 

在正在使用的CustomWebClient的地方,

using (CustomWebClient client = new CustomWebClient()) 
{ 
    client.Headers.Add("HeaderName","Value"); 
    client.Post(); 
} 
+0

听起来像一个计划! –

1

如果可能的话头的数量是有限的,你可以在你的CustomWebClient类声明为public enum创造要么过载constructorUploadString()函数(无论你喜欢哪一个),并将它传递给enum的值以相应地设置标题。例如:

public class CustomWebClient { 
    public enum Headers { StandardForm, Json, Xml } 

    public CustomWebClient() { 
    } 

    //This is your original UploadString. 
    public string UploadString(string x, string y) { 
     //Call the overload with default header. 
     UploadString("...", "...", Headers.StandardForm); 
    }  


    //This is the overloaded UploadString. 
    public string UploadString(string x, string y, Headers header) { 
     switch(header){ 
     case Headers.StandardForm: 
      client.Headers.Add("Content-Type","application/x-www-form-urlencoded"); 
      break; 
     case Headers.Json: 
      client.Headers.Add("Content-Type","text/json"); 
      break; 
     case Headers.Xml: 
      client.Headers.Add("Content-Type","text/xml"); 
      break; 
     } 
     //Continue your code. 
    }  
} 

使用enum是消除可能的拼写错误,并为您智能影音感,这样你就不需要记住你的选择是什么最吸引人的优点。