G0ldenowner
G0ldenowner

Reputation: 39

Cannot initialize type 'HttpClientHandler'

Here is the error I get:

Cannot initialize type 'HttpClientHandler' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

Code:

using System;
using System.Net;
using System.Net.Http;

namespace Sharepoint_2013_REST_API
{
    public class Program
    {
        public void Main(string[] args)
        {
            //Init
            string baseURL = "";
            string uriString = "";
            string User = "";
            string Password = "";
            string Domain = "";

            System.Net.Http.HttpClient _Client = new System.Net.Http.HttpClient();
            _Client.BaseAddress = new Uri(baseURL);
            HttpResponseMessage resp = _Client.GetAsync(uriString).Result;
            string respString = resp.Content.ReadAsStringAsync().Result;

            _Client = new System.Net.Http.HttpClient(new HttpClientHandler() { new NetworkCredential(User, Password, Domain)});

            if (resp.StatusCode != HttpStatusCode.OK)
            {
                Console.Write("Status code: " + resp.StatusCode);
                Console.ReadLine();
            }
        }


    }
}

Hope you can help me resolve this error?

Upvotes: 1

Views: 443

Answers (4)

rory.ap
rory.ap

Reputation: 35308

Here try it this way:

_Client = new System.Net.Http.HttpClient(
    new System.Net.Http.HttpClientHandler() 
    {Credentials = new System.Net.NetworkCredential(User, Password, Domain)});

The part with the brackets is called an object initializer. However, when you don't provide the property you are trying to initialize, i.e. Credentials =, the compiler mistakenly thinks you are trying to provide a collection initializer, not an object initializer.

You would use a collection initializer when initializing a collection, e.g. an array, like this:

string[] myStrings = new[] {"first", "second", "third"};

Upvotes: 1

Oluwafemi
Oluwafemi

Reputation: 14899

The code is incorrect... It should be:

new System.Net.Http.HttpClient(new HttpClientHandler { Credentials = new NetworkCredential(user, pwd, domain)});

Upvotes: 1

Yacoub Massad
Yacoub Massad

Reputation: 27871

You need to specify the property to initialize. In this case, it is the Credentials property.

_Client = 
    new HttpClient(
        new HttpClientHandler
        {
            Credentials = new NetworkCredential(User, Password , Domain)
        });

Upvotes: 1

CharithJ
CharithJ

Reputation: 47570

You have forgotten to assign NewworkCredential instance to the Credentials property in the object initializer.

new HttpClient(new HttpClientHandler() {{Credentials = new System.Net.NetworkCredential(user, pwd, domain)});

Upvotes: 1

Related Questions