. NET access to browser cookies (including HttpOnly) instance sharing _ Practical tips

Source: Internet
Author: User

First, interface file

Copy Code code as follows:

Using System;
Using System.ComponentModel;
Using System.Net;
Using System.Runtime.InteropServices;
Using System.Security;
Using System.Security.Permissions;
Using System.Text;

Namespace Cookiehandler
{
Internal sealed class Inativemethods
{
#region enums

public enum Errorflags
{
Error_insufficient_buffer = 122,
Error_invalid_parameter = 87,
Error_no_more_items = 259
}

public enum Internetflags
{
Internet_cookie_httponly = 8192,//requires IE 8 or higher
Internet_cookie_third_party = 131072,
Internet_flag_restricted_zone = 16
}

#endregion

#region DLL Imports

[SuppressUnmanagedCodeSecurity, SecurityCritical, dllimport ("Wininet.dll", EntryPoint = "Internetgetcookieexw", CharSet = CharSet.Unicode, SetLastError = True, ExactSpelling = True)]
Internal static extern bool Internetgetcookieex ([in] string Url, [into] string cookiename, [out] StringBuilder cookiedata, [ In, out] ref UINT PCHCOOKIEDATA, UINT flags, INTPTR reserved);

#endregion
}
}

Second, get the cookie class

Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Net;
Using System.Runtime.InteropServices;
Using System.Security;
Using System.Security.Permissions;
Using System.Text;

Namespace Cookiehandler
{
<SUMMARY></SUMMARY>
Gets the complete cookie for the WebBrowser.
Because the default WebBrowser1.Document.Cookie cannot get the HttpOnly cookie
IE7 incompatible, IE8 can, other unknown
///
public class Fullwebbrowsercookie
{
public static dictionary<string, string> getcookielist (URI Uri, bool Throwifnocookie)
{
dictionary<string, string> dict = new dictionary<string, string> ();
String cookie = getcookieinternal (URI, Throwifnocookie);
Console.WriteLine ("Fullwebbrowsercookie-All Cookies:" + cookies);
string[] Arrcookie = cookie. Split (';');
foreach (var item in Arrcookie)
{
string[] arr = Item. Split (' = ');
String key = Arr[0]. Trim ();
String val = "";
if (arr. Length >= 2)
{
val = arr[1]. Trim ();
}

if (!dict. ContainsKey (Key))
{
Dict. Add (Key, Val);
}
}
Console.WriteLine ("Fullwebbrowsercookie-cookie has been loaded into Dict, total" + Dict. Count.tostring () + "item");

return dict;
}

public static string Getcookievalue (string key, Uri Uri, bool Throwifnocookie)
{
Console.WriteLine ("Getcookievalue");
dictionary<string, string> dict = Getcookielist (URI, Throwifnocookie);

if (Dict. ContainsKey (Key))
{
return Dict[key];
}
Return "";
}

[SecurityCritical]
public static string getcookieinternal (URI Uri, bool Throwifnocookie)
{
Console.WriteLine ("Getcookieinternal");

UINT Pchcookiedata = 0;
String url = uritostring (URI);
UINT flag = (UINT) INativeMethods.InternetFlags.INTERNET_COOKIE_HTTPONLY;

Gets the size of the string builder
if (Inativemethods.internetgetcookieex (URL, null, NULL, ref pchcookiedata, Flag, IntPtr.Zero))
{
pchcookiedata++;
StringBuilder cookiedata = new StringBuilder ((int) pchcookiedata);

Read the cookie
if (Inativemethods.internetgetcookieex (URL, null, Cookiedata, ref pchcookiedata, Flag, IntPtr.Zero))
{
Demandwebpermission (URI);
return cookiedata.tostring ();
}
}

int lasterrorcode = Marshal.GetLastWin32Error ();

if (Throwifnocookie | | (LastErrorCode!= (int) INativeMethods.ErrorFlags.ERROR_NO_MORE_ITEMS))
{
throw new Win32Exception (LastErrorCode);
}

return null;
}

private static void Demandwebpermission (URI uri)
{
String uristring = Uritostring (URI);

if (URI. Isfile)
{
String localpath = URI. LocalPath;
New FileIOPermission (FileIOPermissionAccess.Read, LocalPath). Demand ();
}
Else
{
New WebPermission (Networkaccess.connect, uristring). Demand ();
}
}

private static string uritostring (Uri uri)
{
if (URI = = null)
{
throw new ArgumentNullException ("uri");
}

UriComponents components = (URI. Isabsoluteuri? UriComponents.AbsoluteUri:UriComponents.SerializationInfoString);
return new StringBuilder (URI. Getcomponents (components, uriformat.safeunescaped), 2083). ToString ();
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.