Witam.
Jak w webclient używać cookie? Tzn. wiem jak ustawić żeby używał konkretne ciasteczka, ale jak zrobić żeby ustawiał je automatycznie i na bieżąco (tak jak przeglądarka)?
Znalazłem takie coś:
public class CookieWebClient : WebClient
{
public CookieContainer CookieContainer { get; private set; }
/// <summary>
/// This will instanciate an internal CookieContainer.
/// </summary>
public CookieWebClient()
{
this.CookieContainer = new CookieContainer();
}
/// <summary>
/// Use this if you want to control the CookieContainer outside this class.
/// </summary>
public CookieWebClient(CookieContainer cookieContainer)
{
this.CookieContainer = cookieContainer;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address) as HttpWebRequest;
if (request == null) return base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
using (var client = new CookieWebClient())
{
var loginData = new NameValueCollection
{
{ "UserName", "TestUser" },
{ "Password", "MyPassword" }
};
// Login into the website (at this point the Cookie Container will do the rest of the job for us, and save the cookie for the next calls)
client.UploadValues("http://domain.com/Account/LogOn", "POST", loginData);
// Call authenticated resources
client.UploadString("http://domain.com/ProtectedArea/MyProtectedResource", "POST", "some data");
}
Tyle że:
Nie można zainicjować obiektu typu "NameValueCollection" za pomocą inicjatora kolekcji
i
Nie można odnaleźć nazwy typu lub przestrzeni nazw "NameValueCollection" (czy nie brakuje dyrektywy "using" lub odwołania do zestawu?)
Pomożecie