I want to display a MediaWiki page in my desktop application using a .NET WebBrowser control. The wiki requires a login. The answer provided here is not acceptable for me because AutoComplete dialogs pop up when using the WebBrowser control.
My approach is to login with a System.Net.WebClient object using api.php?action=clientlogin and then use the cookie that I get to access a wiki page. I can successfully login using the API but when I load a page I'm not logged in.
The code below uses a WebClient object to load the final page. This is for testing purposes and to eliminate another source of error (changing the User-Agent for example).
How do I do this correctly? Am I approaching this wrong?
private void Login(string username, string password)
{
string cookie, loginToken, baseUri = "https://www.mediawiki.org";
var client = new WebClient();
// get logintoken and cookie
using (var stream = client.OpenRead(baseUri + "/w/api.php?action=query&meta=tokens&format=xml&type=login"))
{
cookie = client.ResponseHeaders[HttpResponseHeader.SetCookie].Split(';')[0];
var document = System.Xml.Linq.XDocument.Load(stream);
loginToken = (string)document.XPathEvaluate("string(/api/query/tokens/@logintoken)");
}
// login
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers[HttpRequestHeader.Cookie] = cookie;
var response = client.UploadString(baseUri + "/w/api.php?format=xml", "action=clientlogin&username=" + username +
"&password=" + password + "&loginreturnurl=" + baseUri +
"&logintoken=" + Uri.EscapeDataString(loginToken));
// new cookie (???)
cookie = client.ResponseHeaders[HttpResponseHeader.SetCookie].Split(';')[0];
// success?
if (response.Contains("status=\"PASS\""))
{
client.Headers.Clear();
client.Headers[HttpRequestHeader.Cookie] = cookie;
var data = client.DownloadData(baseUri + "/wiki/API:Login");
var text = Encoding.UTF8.GetString(data); // <--- not logged in
}
}