How to instantiate Webheadercollection using object initializers?

Asked

Viewed 38 times

2

I’m making a requisition with the WebClient and would like to know if it is possible to add a Header within the class instance WebClient, example:

WebClient client = new WebClient(){
    Encoding = System.Text.Encoding.UTF8,
    Headers =new WebHeaderCollection().Add("APIKey",API.APIKey) //Recebo erro aqui pois o retorno de `Add()` é void 
};

I know I could solve by just doing so:

 WebClient client = new WebClient(){
            Encoding = System.Text.Encoding.UTF8
 };
 client.Headers.Add("APIKey",API.APIKey);

But I wonder if it is possible to do what I was doing in the first code without receiving this error.

3 answers

1


It can be done like this:

WebClient client = new WebClient()
{
    Encoding = System.Text.Encoding.UTF8,
    Headers = new WebHeaderCollection()
    {
        ["APIKey"] = "APIKey",
        ["APIKey1"] = "APIKey",
    }
};

because it is a data dictionary and can be accessed this way (Ordered String/Object Collection of name/value pairs with support for null key).

Important also to say that it does not need a new instance, because, Headers is already accessible, so you can reduce to this code:

WebClient client = new WebClient()
{
    Encoding = System.Text.Encoding.UTF8,
    Headers = 
    {
        ["APIKey"] = "APIKey",
        ["APIKey1"] = "APIKey",
    }
};

0

You won’t be able to do it that way, because there is no property public in class WebHeaderCollection to display the list of values in order to be instantiated like this.

View documentation: Webheadercollection

In a very practical way, by opening the { to build the object, it does not have a property to build the headers dictionary, it is only possible using the method Add. It would be something like that if it were possible:

var client = new System.Net.WebClient
{
    Headers = new System.Net.WebHeaderCollection
    {
        { "APIKey",API.APIKey }
    }
};

0

Basically, it is possible to use any method Add that exists in WebHeaderCollection (the type of property Headers).

This is the method used to initialize collections.

For example:

This can be done by separating the key and the value using two-points.

Use the method Add(string)

var client = new WebClient
{
    Encoding = System.Text.Encoding.UTF8,
    Headers = new WebHeaderCollection { $"APIKey: {API.APIKey}" }
};

Or so:

Use the method Add(NameValueCollection)

var client = new WebClient
{
    Encoding = System.Text.Encoding.UTF8,
    Headers = new WebHeaderCollection 
    { 
        { "APIKey", API.APIKey } 
    }
}

Or still, like this:

var client = new WebClient
{
    Encoding = System.Text.Encoding.UTF8,
    Headers = new WebHeaderCollection
    {
        ["APIKey"] = API.APIKey
    }
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.