本文整理汇总了C#中System.Net.Cookie类的典型用法代码示例。如果您正苦于以下问题:C# Cookie类的具体用法?C# Cookie怎么用?C# Cookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Cookie类属于System.Net命名空间,在下文中一共展示了Cookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendLoginData
private async Task<bool> SendLoginData(string username, string password)
{
CookieContainer cookies = await _webManager.PostData(
Constants.LOGIN_URL, string.Format(
"action=login&username={0}&password={1}",
username.Replace(" ", "+"),
WebUtility.UrlEncode(password)));
if (cookies.Count < 2)
{
return false;
}
var fixedCookieContainer = new CookieContainer();
// TODO: HUGE HACK. For some reason Windows Phone does not use the Domain Key on a cookie, but only the domain when making requests.
// Windows 8 won't break on it, but Windows Phone will, since the Domain Key and Domain are different on SA.
// We need to move this code to a more common place.
foreach (Cookie cookie in cookies.GetCookies(new Uri(Constants.COOKIE_DOMAIN_URL)))
{
var fixedCookie = new Cookie(cookie.Name, cookie.Value, "/", ".somethingawful.com");
fixedCookieContainer.Add(new Uri(Constants.COOKIE_DOMAIN_URL), fixedCookie);
}
await _localStorageManager.SaveCookie(Constants.COOKIE_FILE, cookies, new Uri(Constants.COOKIE_DOMAIN_URL));
return true;
}
示例2: ConvertToCookieContainer
/// <summary>
/// convert cookies string to CookieContainer
/// </summary>
/// <param name="cookies"></param>
/// <returns></returns>
public static CookieContainer ConvertToCookieContainer(Dictionary<string, string> cookies)
{
CookieContainer cookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
string[] strEachCookParts = cookie.Value.Split(';');
int intEachCookPartsCount = strEachCookParts.Length;
foreach (string strCNameAndCValue in strEachCookParts)
{
if (!string.IsNullOrEmpty(strCNameAndCValue))
{
Cookie cookTemp = new Cookie();
int firstEqual = strCNameAndCValue.IndexOf("=");
string firstName = strCNameAndCValue.Substring(0, firstEqual);
string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
cookTemp.Name = firstName;
cookTemp.Value = allValue;
cookTemp.Path = "/";
cookTemp.Domain = cookie.Key;
cookieContainer.Add(cookTemp);
}
}
}
return cookieContainer;
}
示例3: Meteor
public Meteor()
{
cookies = new Cookie();
cookies.Domain = "http://www.meteor.ie";
cookies.Name = "meteor";
cookieContainer = new CookieContainer();
}
示例4: GetFormsCredentials
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// Do not use forms credentials to authenticate.
authCookie = null;
user = password = authority = null;
return false;
}
示例5: GetHeaderValue
public string GetHeaderValue(Cookie cookie)
{
var path = cookie.Expires == Session
? "/"
: cookie.Path ?? "/";
var sb = new StringBuilder();
sb.AppendFormat("{0}={1};path={2}", cookie.Name, cookie.Value, path);
if (cookie.Expires != Session)
{
sb.AppendFormat(";expires={0}", cookie.Expires.ToString("R"));
}
if (!string.IsNullOrEmpty(cookie.Domain))
{
sb.AppendFormat(";domain={0}", cookie.Domain);
}
else if (EndpointHost.Config.RestrictAllCookiesToDomain != null)
{
sb.AppendFormat(";domain={0}", EndpointHost.Config.RestrictAllCookiesToDomain);
}
if (cookie.Secure)
{
sb.Append(";Secure");
}
if (cookie.HttpOnly)
{
sb.Append(";HttpOnly");
}
return sb.ToString();
}
示例6: Get
public static bool Get(string route, IEnumerable<KeyValuePair<string, string>> parameters, out JObject result, Cookie cookie = null)
{
KeyValuePair<bool, string> get = GetAsync(route, parameters, cookie).Result;
result = get.Key ? JObject.Parse(get.Value) : null;
return get.Key;
}
示例7: GetFormsCredentials
public bool GetFormsCredentials(out Cookie authCookie, out string user,
out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
示例8: TestDeep
public void TestDeep(string username, string password)
{
Blog service = new Blog();
string ticket = service.Login(username, password);
Cookie cookie = new Cookie(sDBlogAuthCookieName, ticket, "/", "localhost");
TestDeep(cookie);
}
示例9: AuthenticateUser
private static bool AuthenticateUser(string user, string password, out Cookie authCookie)
{
var request = WebRequest.Create("https://localhost/account/LogIn") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
var authCredentials = "UserName=" + user + "&Password=" + password;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
authCookie = response.Cookies[FormsAuthentication.FormsCookieName];
}
if (authCookie != null)
{
return true;
}
else
{
return false;
}
}
示例10: Context
public void Context()
{
File.WriteAllText(AuthenticationCookiePersister.PersistentCookiePath, "nonsence nonsence nonsence nonsence nonsence nonsence nonsence");
var authenticationCookiePersister = new AuthenticationCookiePersister();
_cookie = authenticationCookiePersister.GetPersistentAuthenticationCookie();
}
开发者ID:xhafan,项目名称:eshop-coreddd,代码行数:7,代码来源:when_getting_persistent_cookie_which_cannot_be_deserialized.cs
示例11: OnIdentityProviderTapped
private async void OnIdentityProviderTapped(object sender, TappedRoutedEventArgs e)
{
var identityProvider = (IdentityProvider)((FrameworkElement)e.OriginalSource).DataContext;
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri(identityProvider.LoginUrl),
new Uri("http://authentication.brainthud.com/api/federationcallback/end"));
var start = webAuthenticationResult.ResponseData.LastIndexOf('=') + 1;
var nameIdentifier = webAuthenticationResult.ResponseData.Substring(start, webAuthenticationResult.ResponseData.Length - start);
var cookies = this.getCookies(nameIdentifier);
var uri = new Uri(@"http://www.brainthud.com/api/Cards/");
var cookieContainer = new CookieContainer();
foreach(var cookie in cookies)
{
var cookieItem = new Cookie(cookie.Key, cookie.Value);
cookieContainer.Add(uri, cookieItem);
}
var handler = new HttpClientHandler();
handler.CookieContainer =cookieContainer;
var client = new HttpClient(handler);
var response = client.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
var x = result;
}
示例12: AddCookie
public static void AddCookie(this List<Cookie> cookieList, string setCookieFormat)
{
var bits = setCookieFormat.Split(';');
string key, value;
GetKeyValue(bits[0], '=', out key, out value);
var c = new Cookie(key, value);
for(var i = 1; i < bits.Length; i++) {
GetKeyValue(bits[1], '=', out key, out value);
switch(key) {
case "expires":
c.Expires = DateTime.Parse(value);
break;
case "path":
c.Path = value;
break;
case "domain":
c.Domain = value;
break;
case "secure":
c.Secure = value == "true";
break;
}
}
cookieList.AddCookie(c);
}
示例13: GetFedAuthCookie
/// <summary>
/// Performs active authentication against ADFS using the trust/13/usernamemixed ADFS endpoint.
/// </summary>
/// <param name="siteUrl">Url of the SharePoint site that's secured via ADFS</param>
/// <param name="serialNumber">Serial Number of the Current User > My Certificate to use to authenticate </param>
/// <param name="certificateMixed">Uri to the ADFS certificatemixed endpoint</param>
/// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
/// <param name="logonTokenCacheExpirationWindow"></param>
/// <returns>A cookiecontainer holding the FedAuth cookie</returns>
public CookieContainer GetFedAuthCookie(string siteUrl, string serialNumber, Uri certificateMixed, string relyingPartyIdentifier, int logonTokenCacheExpirationWindow)
{
CertificateMixed adfsTokenProvider = new CertificateMixed();
var token = adfsTokenProvider.RequestToken(serialNumber, certificateMixed, relyingPartyIdentifier);
string fedAuthValue = TransformSamlTokenToFedAuth(token.TokenXml.OuterXml, siteUrl, relyingPartyIdentifier);
// Construct the cookie expiration date
TimeSpan lifeTime = SamlTokenlifeTime(token.TokenXml.OuterXml);
if (lifeTime == TimeSpan.Zero)
{
lifeTime = new TimeSpan(0, 60, 0);
}
int cookieLifeTime = Math.Min((lifeTime.Hours * 60 + lifeTime.Minutes), logonTokenCacheExpirationWindow);
DateTime expiresOn = DateTime.Now.AddMinutes(cookieLifeTime);
CookieContainer cc = null;
if (!string.IsNullOrEmpty(fedAuthValue))
{
cc = new CookieContainer();
Cookie samlAuth = new Cookie("FedAuth", fedAuthValue);
samlAuth.Expires = expiresOn;
samlAuth.Path = "/";
samlAuth.Secure = true;
samlAuth.HttpOnly = true;
Uri samlUri = new Uri(siteUrl);
samlAuth.Domain = samlUri.Host;
cc.Add(samlAuth);
}
return cc;
}
示例14: Get
/// <summary>
/// Get request to a website
/// </summary>
/// <param name="uri">Uri to request</param>
/// <param name="host">Host for header</param>
/// <param name="cookie">Cookie for authentication</param>
/// <param name="referer">Referer for header</param>
/// <param name="action">Callback</param>
/// <param name="userAgent">Useragent for header</param>
/// <remarks>Requires refactoring, make it more general and replace CrawlString with it</remarks>
public static void Get(String uri, String host, Cookie cookie, String referer, Action<PostResult> action, String userAgent)
{
using (var client = new WebClientEx())
{
if (cookie != null)
{
client.CookieContainer.Add(cookie);
}
client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
client.Headers["Accept-Language"] = "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3";
client.Headers["Cache-Control"] = "no-cache";
client.Headers["User-Agent"] = userAgent;
if (!String.IsNullOrEmpty(referer))
{
client.Headers["Referer"] = referer;
}
if (!String.IsNullOrEmpty(host))
{
client.Headers["Host"] = host;
}
client.Headers["X-Requested-With"] = "XMLHttpRequest";
var response = client.DownloadString(uri);
PostResult ps = new PostResult() { Result = response };
action(ps);
}
}
示例15: SendHttpPostRequest
/// <summary>
/// ͬ������HttpRequest
/// </summary>
/// <param name="cookie"></param>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static HttpWebResponse SendHttpPostRequest(Cookie cookie, string url, string postData)
{
//���https�µ�֤������
HttpRequestCredentialHelper.SetDefaultCredentialValidationLogic();
var request = HttpWebRequest.Create(url) as HttpWebRequest;
//������������ΪPOST
request.Method = "POST";
//����Post������
if (!string.IsNullOrEmpty(postData))
{
request.ContentLength = postData.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
writer.Close();
}
}
//��Cookie�����������÷�����֪����ǰ�û������
var container = new CookieContainer();
request.CookieContainer = container;
if (cookie != null)
{
container.SetCookies(new Uri(Constants.ROOT_URL), string.Format("{0}={1}", cookie.Name, cookie.Value));
var logger = DependencyResolver.Resolve<ILoggerFactory>().Create(typeof(HttpWebRequestHelper));
logger.InfoFormat("HttpWebRequest CookieName:{0}, Value:{1}", cookie.Name, cookie.Value);
}
return request.GetResponse() as HttpWebResponse;
}