簡體   English   中英

設置WebClient的自定義標頭

[英]Set custom headers for WebClient

我有一個要與多個供應商聯系的Web客戶端。

除了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()或其他方法設置標頭呢?

我正在努力想出一種行之有效且不會發臭的模式。

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

如果可能的標頭的數量有限,則可以在CustomWebClient類中將它們聲明為public enum ,並創建constructorUploadString()函數(無論您喜歡哪個UploadString()的重載,然后將其傳遞給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最吸引人的好處是消除了可能的拼寫錯誤,並給您了智能的感覺,因此您無需記住自己的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM