public MvcErrorLog(string application, ExceptionContext exceptionContext) : base(application, exceptionContext.Exception) { var context = exceptionContext.HttpContext; if (context == null) { return; } Host = Host ?? TryGetMachineName(context); var user = context.User; if (!(user == null || string.IsNullOrWhiteSpace(user.Identity.Name))) { User = user.Identity.Name; } var request = context.Request; ServerVariables.Add(request.ServerVariables); QueryString.Add(request.QueryString); Form.Add(request.Form); Cookies.Add(request.Cookies); }
/// <summary> /// Ends getting the response and calls the /// callback function assosiated with request. /// </summary> /// <param name="result">Async result.</param> private void EndResponse(IAsyncResult result) { HttpWebResponse response = null; try { response = (HttpWebResponse)(result.AsyncState as HttpWebRequest).EndGetResponse(result); Cookies.Add(response.Cookies); } catch (Exception e) { Logger.Error(e.Message); throw; } if (response != null) { var content = ReadResponse(response); response.Close(); var request = result.AsyncState as HttpWebRequest; if (Requests.ContainsKey(request)) { var callback = Requests[request]; if (callback != null) { callback.Invoke(content, request.Address.OriginalString); } } Requests.Remove(request); } }
private void AddAnyNewCookiesToCookieCollection() { if (LastRequestData.Response == null) { return; } HttpCookieCollection lastResponseCookies = LastRequestData.Response.Cookies; if (lastResponseCookies == null) { return; } foreach (string cookieName in lastResponseCookies) { HttpCookie cookie = lastResponseCookies[cookieName]; if (Cookies[cookieName] != null) { Cookies.Remove(cookieName); } if ((cookie.Expires == default(DateTime)) || (cookie.Expires > DateTime.Now)) { Cookies.Add(cookie); } } }
public void OnEvaluate_ShouldFindResult() { var evaluator = new CookieEvaluator(); var cookies = new Cookies(); cookies.Add(new JsonString("key_str", "value")); cookies.Add(new JsonLong("key_int", 20)); var actual = evaluator.Evaluate("${call1.response.cookies.key_str}", CreateTestResult("call1", cookies)); Assert.AreEqual("value", actual); actual = evaluator.Evaluate("${call1.response.cookie.key_int}", CreateTestResult("call1", cookies)); Assert.AreEqual(20, long.Parse(actual)); }
private void _ParseCookies() { if (Headers.ContainsKey(HttpHeader.Cookie)) { var cookies = Headers.Get(HttpHeader.Cookie); foreach (var cookie in cookies) { if (!cookie.Value.Contains('=')) { return; } var cookieArgs = cookie.Value .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); foreach (var cookieArg in cookieArgs) { var cookieKeyValuePair = cookieArg.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (cookieKeyValuePair.Length == 2) { var key = cookieKeyValuePair[0].Trim(); var value = cookieKeyValuePair[1].Trim(); Cookies.Add(new HttpCookie(key, value, isNew: false)); } } } } }
protected async void Init(HttpResponseMessage rsp) { if (rsp.StatusCode == HttpStatusCode.OK) { this.Data = await rsp.Content.ReadAsByteArrayAsync(); } if (rsp.Headers != null) { foreach (var kv in rsp.Headers) { if ("Set-Cookie".Equals(kv.Key)) { if (Cookies == null) { Cookies = new AsyncCookieContainer(); } foreach (var cookieStr in kv.Value) { Cookies.Add(cookieStr); } } Headers[kv.Key] = string.Join(";", kv.Value); } } StatusCode = rsp.StatusCode; RequestMessage = rsp.RequestMessage; }
internal HttpWebResponse GetResponse(HttpWebRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); Cookies.Add(response.Cookies); // Print the properties of each cookie. Console.WriteLine("\nCookies: "); foreach (Cookie cook in Cookies.GetCookies(request.RequestUri)) { Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook); } } catch (WebException ex) { Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(response); }
public void SetCookie(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } bool added = false; try { Cookies.Add(cookie); added = true; } catch (CookieException) { Debug.Assert(!added); } if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"cookie: {cookie}"); } if (!added) { // cookie already existed and couldn't be replaced throw new ArgumentException(SR.net_cookie_exists, nameof(cookie)); } }
private void ParseCookies() { if (Headers.ContainsHeader("Cookie")) { var cookieValue = Headers.GetHeader("Cookie").Value; if (string.IsNullOrEmpty(cookieValue)) { return; } string[] cookies = cookieValue.Split("; "); foreach (var splitCookie in cookies) { string[] cookieParts = splitCookie.Split('=', 2, StringSplitOptions.RemoveEmptyEntries); if (cookieParts.Length != 2) { continue; } string key = cookieParts[0]; string value = cookieParts[1]; Cookies.Add(new HttpCookie(key, value, false)); } } }
public bool Authenticate() { ExpireCookies(); Cookies.SetCookies(_httpHotelUri, SKore.GetIpCookie(Hotel)); try { byte[] postData = Encoding.UTF8.GetBytes(string.Format("{{\"email\":\"{0}\",\"password\":\"{1}\"}}", Email, Password)); var loginRequest = (HttpWebRequest)WebRequest.Create(string.Format("{0}/api/public/authentication/login", _httpsHotelUri.OriginalString)); loginRequest.ContentType = "application/json;charset=UTF-8"; loginRequest.UserAgent = SKore.ChromeAgent; loginRequest.AllowAutoRedirect = false; loginRequest.CookieContainer = Cookies; loginRequest.Method = "POST"; loginRequest.Proxy = null; using (Stream requestStream = loginRequest.GetRequestStream()) requestStream.Write(postData, 0, postData.Length); using (var response = (HttpWebResponse)loginRequest.GetResponse()) using (var streamReader = new StreamReader(response.GetResponseStream())) { Cookies.Add(response.Cookies); string responseBody = streamReader.ReadToEnd(); UpdateSession(responseBody); } return(true); } catch { return(false); } }
/// <summary> /// 将指定的 Cookie 添加到此响应的 Cookie 集合。 /// </summary> /// <param name="name">cookie名称。</param> /// <param name="value">cookie值。</param> public void AppendCookie(string name, string value) { if (string.IsNullOrEmpty(name)) { Cookies.Add(name, value); } }
private void ParseCookies() { if (!Headers.ContainsHeader(HttpHeader.Cookie)) { return; } string cookiesString = Headers.GetHeader(HttpHeader.Cookie).Value; if (string.IsNullOrEmpty(cookiesString)) { return; } string[] splitCookies = cookiesString.Split(HttpRequestCookiesSeparator); foreach (string splitCookie in splitCookies) { string[] cookieParts = splitCookie.Split(HttpRequestCookieNameValueSeparator, 2, StringSplitOptions.RemoveEmptyEntries); if (cookieParts.Length != 2) { continue; } string key = cookieParts[0]; string value = cookieParts[1]; Cookies.Add(new HttpCookie(key, value, false)); } }
private void HandleAuthentication(string token) { var baseUrl = new Uri(BaseUrl); // hadler with cookie container HttpClientHandler httpHandler = new HttpClientHandler { CookieContainer = CookieJar }; // use token to get a new auth cookie using var client = new HttpClient(httpHandler) { BaseAddress = baseUrl }; var content = new StringContent($"{{jwt: '{token}' }}", Encoding.UTF8, "application/json"); var result = client.PostAsync("/client/sign-in", content).Result; // get cookies IEnumerable <Cookie> responseCookies = CookieJar.GetCookies(baseUrl).Cast <Cookie>(); foreach (Cookie cookie in responseCookies) { Cookies.Add(baseUrl, cookie); } if (!result.IsSuccessStatusCode) { var handler = this.SSOError; if (handler != null) { handler(this, new EventArgs()); } } }
private void AddCookiesSafe(CookieCollection cookies) { if (IsMultiThreaded) { lock (_lock) { foreach (Cookie cookie in cookies) { try { Cookies.Add(cookie); } catch { } } } } else { foreach (Cookie cookie in cookies) { try { Cookies.Add(cookie); } catch { } } } }
public async Task <RedirectResponse> SetCulture() { var culture = (string)Request.Query["l"]; var returnUrl = (string)Request.Query["u"]; // Validate culture = CultureHelper.GetImplementedCulture(culture); var outCookie = string.Empty; if (Cookies.TryGetValue(CultureCookieName, out outCookie)) { Cookies[CultureCookieName] = culture; } else { Cookies.Add(CultureCookieName, culture); } var cookie = Cookies[CultureCookieName]; var response = Context.GetRedirect(returnUrl); response.WithCookie(CultureCookieName, cookie ?? culture, DateTime.Now.AddYears(1)); Analytics.TrackEventAsync(Category.Navbar, PlexRequests.Helpers.Analytics.Action.Language, culture, Username, CookieHelper.GetAnalyticClientId(Cookies)); return(response); }
public virtual void AddCookie(Uri domain, string name, string value) { Cookies.Add(new HttpCookieParameter(name, value) { Domain = domain }); }
private void SetCookies(HttpWebResponse response) { var cookieString = response.Headers[HttpResponseHeader.SetCookie]; var matches = Regex.Matches(cookieString, @"(?<Name>[^=,;\s]*)=(?<Value>[^,;]*)(?:(?:; expires=(?<Expires>[^;]*))|(?:; Max-Age=(?<MaxAge>[0-9]*))|(?:; path=(?<Path>[^,;]*))|(?:; (?<HttpOnly>HttpOnly)))*,?"); foreach (Match match in matches) { var cookie = new Cookie(); if (match.Groups["Name"].Success) { cookie.Name = match.Groups["Name"].Value; } if (match.Groups["Value"].Success) { cookie.Value = match.Groups["Value"].Value; } if (match.Groups["Expires"].Success) { cookie.Expires = DateTime.Parse(match.Groups["Expires"].Value); } if (match.Groups["MaxAge"].Success) { } if (match.Groups["Path"].Success) { cookie.Path = match.Groups["Path"].Value; } cookie.HttpOnly = match.Groups["HttpOnly"].Success; Cookies.Add(cookie); } }
private void ParseCookies() { if (Headers.ContainsHeader(GlobalConstants.HeaderCookieKey)) { var requestCookies = Headers.GetHeader(GlobalConstants.HeaderCookieKey).Value; if (!requestCookies.Contains(GlobalConstants.ParameterKvpSeparator)) { throw new BadRequestException(); } var cookies = requestCookies .Split("; ") .ToArray(); foreach (var cookie in cookies) { var cookieParts = cookie .Split('=', 2) .ToArray(); if (cookieParts.Length != 2) { continue; } var key = cookieParts[0]; var value = cookieParts[1]; var httpCookie = new HttpCookie(key, value, false); Cookies.Add(httpCookie); } } }
private async Task AcceptCookies(HttpClient client) { var dumpert = await client.GetAsync("https://www.dumpert.nl/"); var dumpertResult = await dumpert.Content.ReadAsStringAsync(); await Task.Delay(3000); var date = DateTime.Now.AddDays(1825); Cookies.Add(new System.Net.Cookie("cpc", "10", "/", "dumpert.nl") { Expires = date }); var epochMilliseconds = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds; var r = (long)Math.Floor((1 + epochMilliseconds) * new Random().NextDouble()); var acceptUrl = $"http://dumpert.nl/?kudtcookiewet=jakapmetzeuren&kudtcookiernd={r}"; client.DefaultRequestHeaders.Referrer = new Uri("http://kudtkoekiewet.nl/?t=http://dumpert.nl/"); var cookiePass = await client.GetAsync(acceptUrl); var cookiePassResult = await cookiePass.Content.ReadAsStringAsync(); }
private void ProcessAMFResponse <T>(IAsyncResult asyncResult) { try { AsyncStreamSetInfo <T> asyncStreamSetInfo = (AsyncStreamSetInfo <T>)asyncResult.AsyncState; if (asyncStreamSetInfo.responseThreadConfigurator != null) { asyncStreamSetInfo.responseThreadConfigurator(); } HttpWebRequest request = asyncStreamSetInfo.request; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); if (Cookies != null) { foreach (Cookie cookie in response.Cookies) { Cookies.Add(new Uri(GatewayUrl), cookie); } } Stream streamResponse = response.GetResponseStream(); long curTime = DateTime.Now.Ticks; long roundTrip = (curTime - asyncStreamSetInfo.messageSentTime) / TimeSpan.TicksPerMillisecond; RequestParser parser = new RequestParser(); Request responseObject = parser.readMessage(streamResponse); object[] responseData = (object[])responseObject.getRequestBodyData(); V3Message v3 = (V3Message)((IAdaptingType)responseData[0]).defaultAdapt(); if (v3.isError) { ErrMessage errorMessage = (ErrMessage)v3; Fault fault = new Fault(errorMessage.faultString, errorMessage.faultDetail, errorMessage.faultCode); if (asyncStreamSetInfo.responder != null) { asyncStreamSetInfo.responder.ErrorHandler(fault); } return; } IAdaptingType body = (IAdaptingType)((AnonymousObject)((NamedObject)responseData[0]).TypedObject).Properties["body"]; T result = (T)body.adapt(typeof(T)); if (asyncStreamSetInfo.responder != null) { asyncStreamSetInfo.responder.ResponseHandler(result); } // ProcessV3Message( v3, asyncStreamSetInfo.responder ); } catch (Exception e) { AsyncStreamSetInfo <T> asyncStreamSetInfo = (AsyncStreamSetInfo <T>)asyncResult.AsyncState; ProccessException(e, asyncStreamSetInfo.responder); } }
/// <summary> /// 将指定的 Cookie 添加到此响应的 Cookie 集合。 /// </summary> /// <param name="cookie">cookie。</param> public void AppendCookie(IHttpCookie cookie) { if (cookie == null) { return; } Cookies.Add(cookie.Name, cookie.Value, cookie.Path, cookie.Domain); }
private static void SetCookies(string key, string value, DateTime expiredTime) { HttpCookie cookies = new HttpCookie(key); cookies.Value = value; cookies.Expires = expiredTime; Cookies.Add(cookies); }
/// <summary> /// /// </summary> /// <param name="response"></param> private void SaveCookiesFrom(HttpWebResponse response) { if (response.Cookies.Count > 0) { if (Cookies == null) Cookies = new CookieCollection(); Cookies.Add(response.Cookies); } }
/*--------------------------------------------------------------------------------------------*/ public void SetUserCookie(long?pUserId, bool pRememberMe) { Tuple <Cookie, TimeSpan> pair = AuthUtil.CreateUserIdCookie(pUserId, pRememberMe); Cookie c = pair.Item1; c.Expires = DateTime.UtcNow.Add(pair.Item2); Cookies.Add(c); }
public void AppendCookie(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } Cookies.Add(cookie); }
private void Reset( ) { Cookies.Clear(); foreach (var cookie in webPage.Request_Cookies) { Cookies.Add(cookie); } }
private static void SetCookies(string key, string value) { HttpCookie cookies = new HttpCookie(key); cookies.Value = value; cookies.Expires = DateTime.Now + new TimeSpan(24, 0, 0); Cookies.Add(cookies); }
private void CookieParsing(string data) { string[] allCookies = data.Split(';'); foreach (string s in allCookies) { string[] nameValue = s.Split('='); Cookies.Add(nameValue[0], nameValue[1]); } }
protected void btnSubmit_Click(object sender, EventArgs e) { bool email = reg.Email_Avaiable(txtEmail.Text); bool username = reg.UserName_Avaiable(txtUserName.Text); bool mobile = reg.Mobile_Avaiable(txtMobileCode.Text + txtMobileNumber.Text); lblUserNameAvaility.Text = reg.UserNameIcon; lblEmailAvaiable.Text = reg.EmailIcon; lblMobileVerify.Text = reg.MobileIcon; lblPassword.Text = reg.PasswordStrongMessege(txtPassword.Text); if (email && username && mobile) { reg.Input_Email = txtEmail.Text; reg.Input_FirstName = txtFirstName.Text; reg.Input_Mobile = txtMobileCode.Text + txtMobileNumber.Text; reg.Input_Packege = "free"; reg.Input_Password = txtPassword.Text; reg.Input_SureName = txtSureName.Text; reg.Input_UserName = txtUserName.Text; if (reg.Reg()) { Cookies cookies = new Cookies(); _Cookies = cookies.Add(reg.LoginID, reg.RegID, Request.UserAgent.ToString()); foreach (HttpCookie httpCookie in _Cookies) { Response.Cookies.Add(httpCookie); } int i = 0; foreach (string Name in cookies.CookiesName) { Session[Name] = cookies.CookiesValueEncrypt[i]; i++; } //lblResult.Text += "1="+ reg.Message; Notification notification = new Notification(); notification.AddNotification("Verify your Email Address.", "../EmailVerify", IconDataFeather.mail, reg.Offset, reg.RegID); //lblResult.Text += "2="+reg.RegID+"/ " + notification.ErrorMessage; EMAIL mAIL = new EMAIL(); mAIL.Subject = "Email Confirmation"; mAIL.Messege = "please verify your email. please click http://" + Request.Url.AbsoluteUri.ToString().Replace("create_account", "EmailVerify") + "?=" + reg.EmailCode + "&rid=" + reg.RegID; mAIL.Email = txtEmail.Text; //mAIL.Mail(); Response.Redirect("~/CMS/"); } else { lblResult.Text = reg.Message; } } }
public void AddCookie(string name, string value) { if (!Cookies.ContainsKey(name)) { Cookies.Add(name, value); } else { Cookies[name] = value; } }