无法隐式转换类型' void'到了System.Net.CookieContainer'

时间:2015-02-20 12:18:11

标签: c#

我只是想在我的网络请求中设置一个cookie,但由于错误而无法做到这一点"无法隐式转换类型' void'到' System.Net.CookieContainer'"。

如果下面的代码不起作用 - 你怎么做到这一点?

    public static string GET(string url, string cookieValue, string cookieName)
    {
        string response = "";
        Uri target = new Uri(url);
        var host = target.Host;
        Cookie c = new Cookie(cookieValue, cookieName) { Domain = host };
        CookieContainer cookieContainer = new CookieContainer().Add(c);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "GET";
        request.CookieContainer = cookieContainer;
        WebResponse response1 = request.GetResponse();
        Stream dataStream = response1.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);

        response = reader.ReadToEnd();

        reader.Close();
        response1.Close();
        return response;
    }

1 个答案:

答案 0 :(得分:5)

你的表达试图"链"实例创建new和对Add的调用。 C#允许这样做,但该表达式的结果类型是Add的返回类型,即void,它不能分配给任何东西。

您需要将此行分开

CookieContainer cookieContainer = new CookieContainer().Add(c);
分为两个:

CookieContainer cookieContainer = new CookieContainer();
cookieContainer.Add(c);

或使用{ - }语法调用Add

CookieContainer cookieContainer = new CookieContainer {
    c
};