La risposta di dlev ha funzionato, ma ho avuto problemi nell'implementazione della soluzione ("Il parametro '{0}' non può essere una stringa vuota."), Così ho deciso di scrivere il codice completo nel caso in cui qualcun altro avesse problemi simili .
Il mio obiettivo era quello di ottenere il codice HTML come una stringa, ma avevo bisogno di aggiungere i biscotti alla richiesta web. Questa è la funzione che scarica la stringa utilizzando i cookie:
public static string DownloadString(string url, Encoding encoding, IDictionary<string, string> cookieNameValues)
{
using (var webClient = new WebClient())
{
var uri = new Uri(url);
var webRequest = WebRequest.Create(uri);
foreach(var nameValue in cookieNameValues)
{
webRequest.TryAddCookie(new Cookie(nameValue.Key, nameValue.Value, "/", uri.Host));
}
var response = webRequest.GetResponse();
var receiveStream = response.GetResponseStream();
var readStream = new StreamReader(receiveStream, encoding);
var htmlCode = readStream.ReadToEnd();
return htmlCode;
}
}
Stiamo usando il codice dalla risposta di dlev:
public static bool TryAddCookie(this WebRequest webRequest, Cookie cookie)
{
HttpWebRequest httpRequest = webRequest as HttpWebRequest;
if (httpRequest == null)
{
return false;
}
if (httpRequest.CookieContainer == null)
{
httpRequest.CookieContainer = new CookieContainer();
}
httpRequest.CookieContainer.Add(cookie);
return true;
}
Questo è il modo di utilizzare il codice completo:
var cookieNameValues = new Dictionary<string, string>();
cookieNameValues.Add("varName", "varValue");
var htmlResult = DownloadString(url, Encoding.UTF8, cookieNameValues);
fonte
2016-08-19 09:46:58
Sarebbe difficile, dato che i cookie sono un concetto HTTP. C'è una ragione per cui devi apportare questo cambiamento? – dlev
@dlev - WebRequest creerà un HttpWebRequest basato su uri. Quindi, se voglio prendere in giro la mia propria WebRequest oggetto e/o registrare il mio URI che restituisce anche un WebRequest, allora io non voglio per vincolare il metodo per lavorare solo con un oggetto HttpWebRequest. –
Capisco che il tipo run-time di 'webRequest' sarà' HttpWebRequest'. Ma l'accesso a 'CookieContainer' richiede che il tipo in fase di compilazione sia' HttpWebRequest'. Inoltre, non parlare di te stesso vincolante per HTTP, ma in quel caso, i cookie non significa molto, dal momento che sono un costrutto HTTP – dlev