如何让C#登录到网站
本文关键字:网站 登录 | 更新日期: 2023-09-27 18:00:31
我正试图弄清楚如何让我的C#应用程序登录到我的网站应用程序。我完全不知道从哪里开始。通常在网站上,用户只需输入用户和密码,然后检查或不检查"记住我"按钮并单击登录。我的python框架验证登录,然后在响应的头部设置一个cookie来保存登录cookie。当用户尝试访问某个页面时,它会检查是否能找到cookie,如果能找到,则会让用户保持登录状态。
我完全不知道如何在桌面C#应用程序中进行这样的操作。有人能给我指正确的方向吗?
感谢
我正试图弄清楚如何让我的桌面C#应用程序登录到我的网站应用程序
使用WebClient班
string string loginData = "username=***&passowrd=***&next=/hurt/";
WebClient wc = new WebClient();
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
wc.Headers.Add("Accept-Encoding", "identity");
wc.Headers.Add("Accept-Language", "en-US,en;q=0.8");
wc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
wc.Headers.Add("ContentType", "application/x-www-form-urlencoded");
string response = wc.UploadString("http://xyz.com/accounts/login/", "POST", loginData);
如果您想模拟浏览器,请使用COM。下面的示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Add a reference to "C:'Windows'System32'shdocvw.dll"
namespace BrowserAutomation
{
class Program
{
static void Main(string[] args)
{
var ie = new SHDocVw.InternetExplorer();
// Ensure that ie.Quit() is called at the end via the destructor
var raii = new IE_RAII(ie);
// Just so you can see what's going on for now
ie.Visible = true;
ie.Navigate2("http://www.wellsfargo.com");
var document = GetDocument(ie);
var userid = document.getElementById("userid");
userid.Value = "billy.everyteen";
var password = document.getElementById("password");
password.Value = "monroebot";
var form = document.Forms("signon");
form.Submit();
// Hang out for a while...
System.Threading.Thread.Sleep(10000);
}
// Poor man's check and wait until DOM is ready
static dynamic GetDocument(SHDocVw.InternetExplorer ie)
{
while (true)
{
try
{
return ie.Document;
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.Message != "Error HRESULT E_FAIL has been returned " +
"from a call to a COM component.")
{
throw e;
}
}
System.Threading.Thread.Sleep(1000);
}
}
}
class IE_RAII
{
public IE_RAII(SHDocVw.InternetExplorer ie)
{
_ie = ie;
}
~IE_RAII()
{
_ie.Quit();
}
private SHDocVw.InternetExplorer _ie;
}
}