Reputation: 3731
I was using this code to login and download needed files for about half a year, and now it has started throwing an exception The parameter '{0}' cannot be an empty string. Parameter name: cookie.Domain, I've checked google, it's a popular problem, but I can't understand why? Everything was okay before, and I've not changed any program code, but what could be changed in railwagon cookies so my program can't understand them now?
CookieContainer cookies = new CookieContainer();
CookieAwareWebClient http = new CookieAwareWebClient(cookies);
string sLogin = "name=_______&password=_______&dobav2_login=_______";
http.Headers["Content-type"] = "application/x-www-form-urlencoded";
http.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
string sResponse = http.UploadString("https://www.railwagonlocation.com/en/index.php", sLogin);
richTextBox1.Text = sResponse;
http.DownloadFile("https://www.railwagonlocation.com/export_excel.php?export_type=vagon_list&l=en", "D:\\my_excel.xlsx");
AwareClient
public class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; }
public Uri Uri { get; set; }
public CookieAwareWebClient()
: this(new CookieContainer())
{
}
public CookieAwareWebClient(CookieContainer cookies)
{
this.CookieContainer = cookies;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
HttpWebRequest httpRequest = (HttpWebRequest)request;
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return httpRequest;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
if (setCookieHeader != null)
{
//do something if needed to parse out the cookie.
if (setCookieHeader != null)
{
Cookie cookie = new Cookie(); //create cookie
this.CookieContainer.Add(cookie);
}
}
return response;
}
}
Error on line
this.CookieContainer.Add(cookie);
Also how we can have cookie.Domain parameter here
Cookie cookie = new Cookie(); //create cookie
this.CookieContainer.Add(cookie);
if we just created new cookie?
Upvotes: 1
Views: 1572
Reputation: 5197
Well, all you do is create an empty cookie, you didn't set a domain, name or value and that's what the CookieContainer checks when you attempt to add it. So one solution would be to set the values for that cookie. However, since you already reference the CookieContainer when in your GetRequest override you don't have to do anything with the Set-Cookie Header you get with the Response, the CookieContainer should already have those cookies added.
Upvotes: 1