当前位置: 首页>>代码示例>>C#>>正文


C# Net.Cookie类代码示例

本文整理汇总了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;
        }
开发者ID:Gluco,项目名称:AwfulMetro,代码行数:28,代码来源:AuthenticationManager.cs

示例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;
        }
开发者ID:yonglehou,项目名称:ToolRepository,代码行数:32,代码来源:Http3Helper.cs

示例3: Meteor

 public Meteor()
 {
     cookies = new Cookie();
     cookies.Domain = "http://www.meteor.ie";
     cookies.Name = "meteor";
     cookieContainer = new CookieContainer();
 }
开发者ID:miconico,项目名称:AIB24Base,代码行数:7,代码来源:clsMeteor.cs

示例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;
 }
开发者ID:HarryMcCarney,项目名称:LarrysListApi,代码行数:7,代码来源:ReportServerCredentials.cs

示例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();
        }
开发者ID:ELHANAFI,项目名称:ServiceStack,代码行数:35,代码来源:Cookies.cs

示例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;
        }
开发者ID:Darth-Alex,项目名称:client,代码行数:7,代码来源:Http.cs

示例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;
 }
开发者ID:hatefi-arman,项目名称:Modules,代码行数:7,代码来源:ReportViewer.aspx.cs

示例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);
 }
开发者ID:dblock,项目名称:dblog,代码行数:7,代码来源:Web.PagesTest.cs

示例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;
            }
        }
开发者ID:provenstyle,项目名称:SignalRChat,代码行数:29,代码来源:Program.cs

示例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;
        }
开发者ID:aenmeyk,项目名称:BrainThud,代码行数:29,代码来源:LoginView.xaml.cs

示例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);
 }
开发者ID:piscisaureus,项目名称:coapp,代码行数:25,代码来源:CookieExtensions.cs

示例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;
        }
开发者ID:stijnbrouwers,项目名称:PnP-Sites-Core,代码行数:43,代码来源:CertificateMixed.cs

示例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);
     }
 }
开发者ID:mercutiodesign,项目名称:TradingPostNotifier,代码行数:36,代码来源:ScrapeHelper.cs

示例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;
        }
开发者ID:codesharp,项目名称:cooper,代码行数:41,代码来源:HttpWebRequestHelper.cs


注:本文中的System.Net.Cookie类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。