这是我得到的错误:
无法初始化类型' HttpClientHandler'有一个集合 初始化程序因为它没有实现 ' System.Collections.IEnumerable'
代码:
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();
}
}
}
}
希望你能帮我解决这个错误吗?
答案 0 :(得分:1)
您忘记将NewworkCredential实例分配给对象初始值设定项中的Credentials属性。
new HttpClient(new HttpClientHandler() {{Credentials = new System.Net.NetworkCredential(user, pwd, domain)});
答案 1 :(得分:1)
您需要指定要初始化的属性。在这种情况下,它是Credentials
属性。
_Client =
new HttpClient(
new HttpClientHandler
{
Credentials = new NetworkCredential(User, Password , Domain)
});
答案 2 :(得分:1)
代码不正确......应该是:
new System.Net.Http.HttpClient(new HttpClientHandler { Credentials = new NetworkCredential(user, pwd, domain)});
答案 3 :(得分:1)
以这种方式尝试:
_Client = new System.Net.Http.HttpClient(
new System.Net.Http.HttpClientHandler()
{Credentials = new System.Net.NetworkCredential(User, Password, Domain)});
带括号的部分称为object initializer。但是,如果您未提供要尝试初始化的属性,即Credentials =
,编译器会错误地认为您正在尝试提供集合初始值设定项,而不是对象初始化程序。
初始化集合时,您可以使用集合初始值设定项,例如一个数组,像这样:
string[] myStrings = new[] {"first", "second", "third"};