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


C# Web.HttpCookie类代码示例

本文整理汇总了C#中System.Web.HttpCookie的典型用法代码示例。如果您正苦于以下问题:C# HttpCookie类的具体用法?C# HttpCookie怎么用?C# HttpCookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpCookie类属于System.Web命名空间,在下文中一共展示了HttpCookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Page_Init

        protected void Page_Init(object sender, EventArgs e)
        {
            // El código siguiente ayuda a proteger frente a ataques XSRF
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Utilizar el token Anti-XSRF de la cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generar un nuevo token Anti-XSRF y guardarlo en la cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }
开发者ID:UamNet,项目名称:TechTalks,代码行数:31,代码来源:Site.Master.cs

示例2: SignIn

        public virtual void SignIn(Customer customer, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            _httpContext.Response.Cookies.Add(cookie);
            _cachedCustomer = customer;
        }
开发者ID:kouweizhong,项目名称:NopCommerce,代码行数:31,代码来源:FormsAuthenticationService.cs

示例3: GetCookieValue

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCookieValue(string name)
        {
            HttpCookie myCookie = new HttpCookie("_languageId");
            myCookie = HttpContext.Current.Request.Cookies["_languageId"];

            return HttpContext.Current.Request.Cookies[name].Value;
        }
开发者ID:omidnasri,项目名称:Implement-a-Generic-Repository-and-a-Unit-of-Work-Class,代码行数:12,代码来源:CookieHelper.cs

示例4: UserAuthenticate

        protected void UserAuthenticate(object sender, AuthenticateEventArgs e)
        {
            if (Membership.ValidateUser(this.LoginForm.UserName, this.LoginForm.Password))
            {
                e.Authenticated = true;
                return;
            }

            string url = string.Format(
                this.ForumAuthUrl,
                HttpUtility.UrlEncode(this.LoginForm.UserName),
                HttpUtility.UrlEncode(this.LoginForm.Password)
                );

            WebClient web = new WebClient();
            string response = web.DownloadString(url);

            if (response.Contains(groupId))
            {
                e.Authenticated = Membership.ValidateUser("Premier Subscriber", "danu2HEt");
                this.LoginForm.UserName = "Premier Subscriber";

                HttpCookie cookie = new HttpCookie("ForumUsername", this.LoginForm.UserName);
                cookie.Expires = DateTime.Now.AddMonths(2);

                Response.Cookies.Add(cookie);
            }
        }
开发者ID:mrkurt,项目名称:mubble-old,代码行数:28,代码来源:Login.aspx.cs

示例5: LogOn

        public ActionResult LogOn(LoginModel model, string returnUrl)
        {
            ViewBag.Message = "Please enter username and password for login.";
            if (ModelState.IsValid)
            {
                User user = ValidateUser(model.username, model.password);

                if (user != null)
                {

                    var authTicket = new FormsAuthenticationTicket(1, model.username, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe,
                                                                "1");
                    string cookieContents = FormsAuthentication.Encrypt(authTicket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                    {
                        Expires = authTicket.Expiration,
                        Path = FormsAuthentication.FormsCookiePath
                    };
                    Response.Cookies.Add(cookie);

                    if (!string.IsNullOrEmpty(returnUrl))
                        Response.Redirect(returnUrl);

                    return RedirectToAction("Index", "Dashboard");
                }
                else
                {
                    ViewBag.Message = "The user name or password provided is incorrect. Please try again";
               }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
开发者ID:aminul,项目名称:NewTest,代码行数:34,代码来源:LoginController.cs

示例6: SetUserAndCookie

    public static void SetUserAndCookie(this HttpContext context, string login, bool isSetCookie = true)
    {
      if (login == null)
      {
        System.Web.Security.FormsAuthentication.SignOut();
        context.User = null;
      }
      else
      {
        if (isSetCookie)
        {
          var authTicket = new System.Web.Security.FormsAuthenticationTicket
            (
               1, //version
               login, // user name
               DateTime.Now,             //creation
               DateTime.Now.AddYears(50), //Expiration (you can set it to 1 month
               true,  //Persistent
               login
            ); // additional informations
          var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);

          var authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);

          authCookie.Expires = authTicket.Expiration;
          authCookie.HttpOnly = true;

          context.Response.SetCookie(authCookie);
        }
        context.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(login), Array<string>.Empty);
      }
    }
开发者ID:undyings,项目名称:NitroBolt.Wui,代码行数:32,代码来源:AuthHlp.cs

示例7: cookieUse

 public void cookieUse(string name, string value, int day)
 {
     HttpCookie cookie = new HttpCookie(name);
     cookie.Value = value;
     cookie.Expires = DateTime.Today.AddDays(day);
     Response.Cookies.Add(cookie);
 }
开发者ID:Lanseria,项目名称:Limon-Studio,代码行数:7,代码来源:game.aspx.cs

示例8: Index

        public ActionResult Index(SignInModel signIn)
        {
            if (!ModelState.IsValid) return View();
            // Hash password
            var password = CreatePasswordHash(signIn.Password);
            // If user found in the db
            var user = db.Users.FirstOrDefault(u => u.Username == signIn.Username && u.Password == password);

            if (user != null)
            {
                // Create cookie
                var cookie = new HttpCookie("User");
                cookie.Values["UserName"] = signIn.Username;
                cookie.Values["UserId"] = user.UserId.ToString();
                cookie.Values["Role"] = user.Role.RoleId.ToString();
                // If remember me, keep the cookie for one year
                cookie.Expires.AddDays(signIn.RememberMe ? 365 : 1);

                HttpContext.Response.Cookies.Remove("User");
                HttpContext.Response.SetCookie(cookie);
                return RedirectToAction("Index", "Home");
            }
            else
                ModelState.AddModelError("", "The user name or password provided is incorrect.");

            return View();
        }
开发者ID:xLs51,项目名称:SynchronicWorld,代码行数:27,代码来源:AccountController.cs

示例9: GetSetProperties

		private void GetSetProperties (HttpCookie biscuit)
		{
			Assert.IsNull (biscuit.Domain, "Domain");
			biscuit.Domain = String.Empty;

			Assert.AreEqual (DateTime.MinValue, biscuit.Expires, "Domain");
			biscuit.Expires = DateTime.MaxValue;

			Assert.IsFalse (biscuit.HasKeys, "HasKeys");
			biscuit["mono"] = "monkey";
			Assert.AreEqual ("monkey", biscuit["mono"], "this");

			Assert.IsNull (biscuit.Name, "Name");
			biscuit.Name = "my";

			Assert.AreEqual ("/", biscuit.Path, "Path");
			biscuit.Path = String.Empty;

			Assert.IsFalse (biscuit.Secure, "Secure");
			biscuit.Secure = true;

			Assert.IsTrue (biscuit.Value.IndexOf ("mono=monkey") >= 0, "Value");
			biscuit.Value = "monkey=mono&singe=monkey";
#if NET_2_0
			Assert.IsFalse (biscuit.HttpOnly, "HttpOnly");
			biscuit.HttpOnly = true;
#endif
		}
开发者ID:nobled,项目名称:mono,代码行数:28,代码来源:HttpCookieCas.cs

示例10: Login

        public ActionResult Login(LoginViewModel model)
        {
            string encryptedPass = Cryption.EncryptText(model.Password);
            //string decryptedPass = Cryption.DecryptText("PBilQKknnyuw05ks6TgWLg==");

            User user = userRepo.GetUserAuth(model.Email, encryptedPass);
            if (user != null)
            {
                user.LastActivity = DateTime.Now;
                user.PublicIP = Utility.GetPublicIP();
                userRepo.Save();

                HttpCookie userCookie = new HttpCookie("USER", model.Email);
                if (model.RememberMe)
                    userCookie.Expires = DateTime.Now.AddMonths(1);
                else
                    userCookie.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Add(userCookie);

                return RedirectToAction("index", "dashboard");
            } 
            ViewBag.Message = "<div class='alert alert-danger'>"
                                     + " <button class='close' data-close='alert'></button>"
                                     + " <span>Kullanıcı adı/Parola geçersizdir. </span>"
                                 + " </div>";
            return View();
        }
开发者ID:abdurrahman,项目名称:UAKasaTakip,代码行数:27,代码来源:AccountController.cs

示例11: SetResponse

		/// <summary>
		/// set http response cookies
		/// </summary>
		/// <param name="response"></param>
		/// <param name="companyUserSesson">if null-remove cookie</param>
		public void SetResponse ( HttpResponseBase response , CompanyUserSession companyUserSesson )
		{
			if (companyUserSesson != null)
			{

				if (response.Cookies[SessionIdCookieName] == null)
				{
					HttpCookie sidCookie = new HttpCookie(SessionIdCookieName, companyUserSesson.Sid);
					response.Cookies.Add(sidCookie);
				}
				else
				{
					response.Cookies[SessionIdCookieName].Value = companyUserSesson.Sid;
				}
				if (response.Cookies[UserIdCookieName] == null)
				{
					HttpCookie uIdCookie = new HttpCookie(UserIdCookieName, companyUserSesson.CompanyUserId.ToString());
					response.Cookies.Add(uIdCookie);
				}
				else
				{
					response.Cookies[UserIdCookieName].Value = companyUserSesson.CompanyUserId.ToString();
				}
			}
			else
			{
				HttpCookie uIdCookie = new HttpCookie(UserIdCookieName, "") {Expires = DateTime.Now};
				response.Cookies.Add ( uIdCookie );
				HttpCookie sidCookie = new HttpCookie(SessionIdCookieName, "") {Expires = DateTime.Now};
				response.Cookies.Add ( sidCookie );
			}
		}
开发者ID:alexey-aristov,项目名称:Advertising,代码行数:37,代码来源:AuthProvider.cs

示例12: CreateNewCookie

 private static HttpCookie CreateNewCookie()
 {
     var cookie = new HttpCookie(COOKIE_ID);
     HttpContext.Current.Response.AppendCookie(cookie);
     HttpContext.Current.Request.Cookies.Add(cookie);
     return cookie;
 }
开发者ID:thatpaulschofield,项目名称:MusicInstructor,代码行数:7,代码来源:CookieAuthenticationSession.cs

示例13: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            //first get the cookie on the incoming request.
            HttpCookie myCookie = new HttpCookie("ExhibitorCookie");
            myCookie = Request.Cookies["ExhibitorCookie"];

            string GUID = myCookie.Value.ToString().Replace("GUID=", "");

            // Read the cookie information and display it.
            if (myCookie != null)
            {//Response.Write ("<p>" + GUID + "</p><p>" + myCookie.Value.ToString() + "</p>");
            }
            else
            {
                Label1.Text = "not found";
            }
            //second get the attendeeID from the URL.
            string AttendeeID = Request.QueryString["Attendee"];
            string MessageToScreen = CommonFunctions.GetExhibitorNamebyGUID(GUID) + " has been visited by " + CommonFunctions.GetAttendeeName(AttendeeID);
            if (string.IsNullOrEmpty(AttendeeID))
            {
                Label1.Text = "No Attendee....";
            }
            else
            {
                Label1.Text = MessageToScreen;
            }

            //third, grab name of exhibitor from db using cookie

            //optional, grab attendees name out of the database.

            //log it to tblLog, exhibitor and name of attendee.
            CommonFunctions.eventToLogDB(MessageToScreen);
        }
开发者ID:r3adm3,项目名称:cSharp-vs2010,代码行数:35,代码来源:RegisterAttendee.aspx.cs

示例14: ResetLoginSession

 public static void ResetLoginSession(int MID)
 {
     MemCache.clear();
     System.Web.HttpCookie hc = new System.Web.HttpCookie("Resx", string.Empty);
     hc.Expires = DateTime.Now.AddDays(-20);
     System.Web.HttpContext.Current.Response.SetCookie(hc);
 }
开发者ID:Xiaoyuyexi,项目名称:LMS,代码行数:7,代码来源:U.cs

示例15: SignIn

        public ActionResult SignIn(SignInViewModel logInViewModel)
        {
            if (ModelState.IsValid)
            {
                string errorMessage;
                User user = _accountService.ValidateUser(logInViewModel.UserName, logInViewModel.Password, out errorMessage);
                if (user != null)
                {
                    SimpleSessionPersister.Username = user.Username;
                    SimpleSessionPersister.Roles = user.Roles.Select(x => x.Name).ToList();
                    if (logInViewModel.StayLoggedIn)
                    {
                        FormsAuthenticationTicket formsAuthenticationTicket = new FormsAuthenticationTicket(SimpleSessionPersister.Username, true, 10080);
                        string encrypt = FormsAuthentication.Encrypt(formsAuthenticationTicket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
                        Response.Cookies.Add(cookie);
                    }

                    return RedirectToAction("Index", "Feed");
                }
                ModelState.AddModelError(string.Empty, errorMessage);
            }

            return View();
        }
开发者ID:ekutsenko-softheme,项目名称:clouduri,代码行数:25,代码来源:ProfileController.cs


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