为WebClient设置自定义标头

时间:2015-11-03 14:57:26

标签: c# asp.net 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()或其他东西设置标题?

我努力想出一种既有效又无味的模式。

2 个答案:

答案 0 :(得分:2)

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

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();
}

答案 1 :(得分:1)

如果可能的标头数量有限,您可以在public enum类中将其声明为CustomWebClient,并创建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最吸引人的好处是消除了可能的拼写错误并为您提供智能感,因此您无需记住您的选择。