How do you set a cookie for a web request in Silverlight
I want to set a cookie value for a http POST request, caqn this be done in Silverlight?
If so which开发者_StackOverflow中文版 class should I use HttpWebRequest, WebCLient or something else?
I think you can define the headers with the HttpWebRequest
, so it's easy just define the Cookie
header with the correct value, you can find a little help here.
To set the cookie:
HtmlPage.Document.SetProperty("cookie", value);
where value is something like "mykey=abcdef;". To read it (key in this case is "mykey":
string[] cookies = HtmlPage.Document.Cookies.Split(';');
foreach (string cookie in cookies)
{
string[] keyValuePair = cookie.Split('=');
if (keyValuePair.Length == 2 && key == keyValuePair[0].Trim())
return keyValuePair[1].Trim();
}
To delete it:
string oldCookie = HtmlPage.Document.GetProperty("cookie") as String;
DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
HtmlPage.Document.SetProperty("cookie", cookie);
精彩评论