我是C#的新手,我正在尝试使用Web服务进行身份验证。他们提供的示例代码显示了一个虚拟类(DataStorageAdapter)。我怎样才能使用sessionid获取cookie?这是示例代码。
System.Net.CookieContainer cookieContainer = DataStorageAdapter.GetCookie("ASP.NET_SessionId") ?? new System.Net.CookieContainer();
以下是完整的代码:
// We need a cookie that we will use in later webservice calls.
// Check if we already have a cookie saved in our system, if not, create a new one
// DataStorageAdapter is a dummy-class for this example only. You will replace this with your preferred method of storing information.
System.Net.CookieContainer cookieContainer = DataStorageAdapter.GetCookie("ASP.NET_SessionId") ?? new System.Net.CookieContainer();
// Lets initialize a Authentication Service with the cookie we have saved (or a new one if we didn't have a cookie saved)
using (Webservice.Authenticate.Authenticate authService = new Webservice.Authenticate.Authenticate { CookieContainer = cookie })
{
// Check whether the ASP.NET_SessionId is still alive in 24SevenOffice's system. If it is not, log in again.
if (!authService.HasSession())
{
// We use a credential object for logging in
// Type is either Community or Client. A community login will always be an email address.
Webservice.Authenticate.Credential credential = new Webservice.Authenticate.Credential
{
Username = "myUserName",
Password = GetMD5("myPassword"), // See below for a MD5 encoding example method
ApplicationId = new Guid("00000000-0000-0000-0000-000000000000"), //YOUR ID HERE
IdentityId = new Guid("00000000-0000-0000-0000-000000000000") //Default is empty guid (no need to edit this)
};
// Do the actual log in
String sessionId = authService.Login(credential);
if (string.IsNullOrEmpty(sessionId))
{
//Login returned empty string, login has failed.
throw new Exception("Error logging into WebService, Username/Password perhaps wrong?");
}
//Login was successful
//Add cookie to old domain to use the old/legacy webservices under webservices.24sevenoffice.com
cookieContainer.Add(new Cookie("ASP.NET_SessionId", sessionId) { Domain = "webservices.24sevenoffice.com" });
//Save the cookie for later use so we do not need to call the Login method too often.
DataStorageAdapter.SetCookie("ASP.NET_SessionId", cookie);
}
//The two next lines are only needed if you wish to change from your default community ID.
//Get a list of possible identities
Webservice.Authenticate.Identity[] myIdentities = authService.GetIdentities();
//Select desired identity (Alternatively, save the Identity.Id the same way you save SessionId, and use authService.SetIdentityById(Guid) )
authService.SetIdentity(myIdentities[0]);