public void NonSecureRequest_AddNoCertificates_CertificateContextNotSet() { using (var handler = new WinHttpHandler()) using (HttpResponseMessage response = SendRequestHelper.Send( handler, () => { }, TestServer.FakeServerEndpoint)) { Assert.Equal(0, APICallHistory.WinHttpOptionClientCertContext.Count); } }
public static HttpResponseMessage Send(WinHttpHandler handler, Action setup, string fakeServerEndpoint) { TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody); setup(); var invoker = new HttpMessageInvoker(handler, false); var request = new HttpRequestMessage(HttpMethod.Get, fakeServerEndpoint); Task<HttpResponseMessage> task = invoker.SendAsync(request, CancellationToken.None); return task.GetAwaiter().GetResult(); }
public void SecureRequest_AddValidCertificate_ValidCertificateContextSet(X509Certificate2 certificate) { using (var handler = new WinHttpHandler()) { handler.ClientCertificates.Add(certificate); using (HttpResponseMessage response = SendRequestHelper.Send( handler, () => { }, TestServer.FakeSecureServerEndpoint)) { Assert.Equal(1, APICallHistory.WinHttpOptionClientCertContext.Count); Assert.NotEqual(IntPtr.Zero, APICallHistory.WinHttpOptionClientCertContext[0]); } } }
public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy; }
public void MaxConnectionsPerServer_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = -1; }); }
public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly() { var handler = new WinHttpHandler(); Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy); }
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; }
public void ConnectTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromSeconds(0); }); }
public void CookieContainer_WhenCreated_ReturnsNull() { var handler = new WinHttpHandler(); Assert.Null(handler.CookieContainer); }
public void ReceiveDataTimeout_SetInfiniteValue_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan; }
public void SslProtocols_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.SslProtocols = (SslProtocols)4096; }); }
public static HttpResponseMessage Send(WinHttpHandler handler, Action setup) { return Send(handler, setup, TestServer.FakeServerEndpoint); }
public async Task <Action <HttpClient> > DoOAuthRequestAsync(string baseUrl, string oauthSource, string apiKey) { if (oauthSource == null) { throw new ArgumentNullException("oauthSource"); } string serverRSAExponent = null; string serverRSAModulus = null; string challenge = null; // Note that at two tries will be needed in the normal case. // The first try will get back a challenge, // the second try will try authentication. If something goes wrong server-side though // (e.g. the server was just rebooted or the challenge timed out for some reason), we // might get a new challenge back, so we try a third time just in case. int tries = 0; while (true) { tries++; #if !DNXCORE50 var handler = new WebRequestHandler(); #else var handler = new WinHttpHandler(); #endif using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation("grant_type", "client_credentials"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json") { CharSet = "UTF-8" }); string data = null; if (!string.IsNullOrEmpty(serverRSAExponent) && !string.IsNullOrEmpty(serverRSAModulus) && !string.IsNullOrEmpty(challenge)) { var exponent = OAuthHelper.ParseBytes(serverRSAExponent); var modulus = OAuthHelper.ParseBytes(serverRSAModulus); var apiKeyParts = apiKey.Split(new[] { '/' }, StringSplitOptions.None); if (apiKeyParts.Length > 2) { apiKeyParts[1] = string.Join("/", apiKeyParts.Skip(1)); } if (apiKeyParts.Length < 2) { throw new InvalidOperationException("Invalid API key"); } var apiKeyName = apiKeyParts[0].Trim(); var apiSecret = apiKeyParts[1].Trim(); data = OAuthHelper.DictionaryToString(new Dictionary <string, string> { { OAuthHelper.Keys.RSAExponent, serverRSAExponent }, { OAuthHelper.Keys.RSAModulus, serverRSAModulus }, { OAuthHelper.Keys.EncryptedData, OAuthHelper.EncryptAsymmetric(exponent, modulus, OAuthHelper.DictionaryToString(new Dictionary <string, string> { { OAuthHelper.Keys.APIKeyName, apiKeyName }, { OAuthHelper.Keys.Challenge, challenge }, { OAuthHelper.Keys.Response, OAuthHelper.Hash(string.Format(OAuthHelper.Keys.ResponseFormat, challenge, apiSecret)) } })) } }); } var requestUri = oauthSource; var response = await httpClient.PostAsync(requestUri, data != null?(HttpContent) new CompressedStringContent(data, true) : new StringContent("")).AddUrlIfFaulting(new Uri(requestUri)).ConvertSecurityExceptionToServerNotFound(); if (response.IsSuccessStatusCode == false) { // We've already tried three times and failed if (tries >= 3) { throw ErrorResponseException.FromResponseMessage(response); } if (response.StatusCode != HttpStatusCode.PreconditionFailed) { throw ErrorResponseException.FromResponseMessage(response); } var header = response.Headers.GetFirstValue("WWW-Authenticate"); if (header == null || header.StartsWith(OAuthHelper.Keys.WWWAuthenticateHeaderKey) == false) { throw new ErrorResponseException(response, "Got invalid WWW-Authenticate value"); } var challengeDictionary = OAuthHelper.ParseDictionary(header.Substring(OAuthHelper.Keys.WWWAuthenticateHeaderKey.Length).Trim()); serverRSAExponent = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAExponent); serverRSAModulus = challengeDictionary.GetOrDefault(OAuthHelper.Keys.RSAModulus); challenge = challengeDictionary.GetOrDefault(OAuthHelper.Keys.Challenge); if (string.IsNullOrEmpty(serverRSAExponent) || string.IsNullOrEmpty(serverRSAModulus) || string.IsNullOrEmpty(challenge)) { throw new InvalidOperationException("Invalid response from server, could not parse raven authentication information: " + header); } continue; } using (var stream = await response.GetResponseStreamWithHttpDecompression()) using (var reader = new StreamReader(stream)) { var currentOauthToken = reader.ReadToEnd(); CurrentOauthToken = currentOauthToken; CurrentOauthTokenWithBearer = "Bearer " + currentOauthToken; ScheduleTokenRefresh(oauthSource, apiKey); return((Action <HttpClient>)(SetAuthorization)); } } } }
public ServiceModelHttpMessageHandler() { _innerHandler = new WinHttpHandler(); InnerHandler = _innerHandler; }
public static HttpResponseMessage Send(WinHttpHandler handler, Action setup) { return(Send(handler, setup, TestServer.FakeServerEndpoint)); }
public void AutomaticRedirection_CtorAndGet_DefaultValueIsTrue() { var handler = new WinHttpHandler(); Assert.True(handler.AutomaticRedirection); }
public Polymath(VaultClientSettings vaultClientSettings) { VaultClientSettings = vaultClientSettings; #if NET45 var handler = new WebRequestHandler(); // if auth method is kerberos, then set the credentials in the handler. if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Kerberos) { var kerberosAuthMethodInfo = vaultClientSettings.AuthMethodInfo as KerberosAuthMethodInfo; handler.PreAuthenticate = kerberosAuthMethodInfo.PreAuthenticate; handler.Credentials = kerberosAuthMethodInfo.Credentials; } #elif NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 var handler = new WinHttpHandler(); // if auth method is kerberos, then set the credentials in the handler. if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Kerberos) { var kerberosAuthMethodInfo = vaultClientSettings.AuthMethodInfo as KerberosAuthMethodInfo; handler.PreAuthenticate = kerberosAuthMethodInfo.PreAuthenticate; handler.ServerCredentials = kerberosAuthMethodInfo.Credentials; } #else var handler = new HttpClientHandler(); // if auth method is kerberos, then set the credentials in the handler. if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Kerberos) { var kerberosAuthMethodInfo = vaultClientSettings.AuthMethodInfo as KerberosAuthMethodInfo; handler.PreAuthenticate = kerberosAuthMethodInfo.PreAuthenticate; handler.Credentials = kerberosAuthMethodInfo.Credentials; } #endif // not the best place, but a very convenient place to add cert of certauthmethod. if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Cert) { var certAuthMethodInfo = vaultClientSettings.AuthMethodInfo as CertAuthMethodInfo; if (certAuthMethodInfo.ClientCertificate != null) { handler.ClientCertificates.Add(certAuthMethodInfo.ClientCertificate); } else { if (certAuthMethodInfo.ClientCertificateCollection != null) { handler.ClientCertificates.AddRange(certAuthMethodInfo.ClientCertificateCollection); } } } vaultClientSettings.PostProcessHttpClientHandlerAction?.Invoke(handler); _httpClient = VaultClientSettings.MyHttpClientProviderFunc == null ? new HttpClient(handler) : VaultClientSettings.MyHttpClientProviderFunc(handler); _httpClient.BaseAddress = new Uri(VaultClientSettings.VaultServerUriWithPort); if (VaultClientSettings.VaultServiceTimeout != null) { _httpClient.Timeout = VaultClientSettings.VaultServiceTimeout.Value; } if (VaultClientSettings.AuthMethodInfo != null) { _authMethodLoginProvider = AuthProviderFactory.CreateAuthenticationProvider(VaultClientSettings.AuthMethodInfo, this); SetVaultTokenDelegate(); } }
public IServiceProvider ConfigureServices(IServiceCollection services) { //screw this app insights var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions(); aiOptions.EnableAdaptiveSampling = false; services.AddApplicationInsightsTelemetry(aiOptions); //asp.net core mvc creates an instance of this class //so there is no need to make singleton //LoggerFactory service _loggerFactory.AddDebug(); //kendo UI //services.AddKendo; //Themeable Razor View Engine services.Configure <RazorViewEngineOptions>(options => { options.ViewLocationExpanders.Add(new ThemeableViewLocationExpander()); }); //init plugins var mvcCoreBuilder = services.AddMvc(); //services.AddMvcCore(); PluginManager.Initialize(mvcCoreBuilder.PartManager); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); //services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>(); //ctl make it from appSettings.json var config = new GrandConfig(); //register autofac dependencies var autofacServiceProvider = this.RegisterDependencies(services, config); //register mapper configurations this.RegisterMapperConfiguration(config); //startup tasks if (false)//!config.IgnoreStartupTasks) { this.RunStartupTasks(); } //Install-Package System.Net.Http.WinHttpHandler -Version 4.3.1 WinHttpHandler httpHandler = new WinHttpHandler() { SslProtocols = SslProtocols.Tls12 }; HttpClient client = new HttpClient(httpHandler); //new //return new AutofacServiceProvider(applicationContainer); //return autofacServiceProvider; //previous return(autofacServiceProvider); }
public void SslProtocols_SetUsingNone_Success() { var handler = new WinHttpHandler(); handler.SslProtocols = SslProtocols.None; }
public async Task <IActionResult> Pay(int price) { try { //ایجاد یک شی از جدول ثبت اطلاعات فرآیند پرداخت Payment payment = new Payment(); payment.Amount = price; payment.ReferenceNumber = 0; // شماره آی دی جدول کاربر var userId = _contextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; payment.UserId = userId; _context.Add(payment); await _context.SaveChangesAsync(); int paymentId = payment.PaymentId; WinHttpHandler httpHandler = new WinHttpHandler(); httpHandler.MaxConnectionsPerServer.Equals(int.MaxValue); httpHandler.SslProtocols = SslProtocols.Tls12; // آدرس برگشت از درگاه string redirectPage = "http://*****:*****@Info.com", "09010487144", redirectPage); // بررسی وضعیت if (paymentReques.Result.Body.Status == 100) { authority = paymentReques.Result.Body.Authority; // اتصال به درگاه Response.Redirect("https://www.zarinpal.com/pg/StartPay/" + authority); } else { // ویرایش اطلاعات ارسالی از زرین پال در صورت عدم اتصال Payment editPayment = _context.Payment.Find(paymentId); if (editPayment != null) { // ویرایش خطای عدم اتصال به درگاه editPayment.StatusPayment = Convert.ToString(paymentReques); _context.Update(editPayment); await _context.SaveChangesAsync(); } // نمایش خطا به کاربر ViewData["Message"] = ZarinPalResult.Status(paymentReques.Result.Body.Status.ToString()); ViewData["SumCountPrice"] = price; } } catch (Exception ex) { string error = ex.Message; ViewData["Message"] = "در حال حاضر امکان اتصال به این درگاه وجود ندارد"; ViewData["SumCountPrice"] = price; } return(View()); }
public void SslProtocols_SetUsingNone_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.SslProtocols = SslProtocols.None; }); }
public ActionResult Return(int saleOrderId) { try { //حتی می توان ورودی های برگشتی از وب سرویس را بصورت ویو مدل دریافت کرد، یا از طریق ورودی مانند بالا، و یا //همانند پایین httpcobtext string saleOrderIdQuery = _contextAccessor.HttpContext.Request.Query["saleOrderId"]; //getting null string StatusQuery = _contextAccessor.HttpContext.Request.Query["Status"]; //getting null string AuthorityQuery = _contextAccessor.HttpContext.Request.Query["Authority"]; //getting null if (saleOrderIdQuery != "" && StatusQuery != "" && StatusQuery != null && AuthorityQuery != "" && AuthorityQuery != null) { // بررسی وضعیت پرداخت if (StatusQuery.ToString().Equals("OK")) { int paymentId = Convert.ToInt32(saleOrderId); // پیدا کردن مبلغ پرداختی از دیتابیس int amount = FindAmountPayment(paymentId); // شماره پیگیری long refId = 0; //System.Net.ServicePointManager.Expect100Continue = false; WinHttpHandler httpHandler = new WinHttpHandler(); httpHandler.MaxConnectionsPerServer.Equals(int.MaxValue); httpHandler.SslProtocols = SslProtocols.Tls12; // ایجاد یک شی از وب سرویس اتصال به درگاه زرین پال var zp = new ZarinpalServiceReference.PaymentGatewayImplementationServicePortTypeClient(); // کد پذیرنده string merchantCode = "501a433c-6d2f-11e7-b90f-033c295111fc"; // وری فای کردن اطلاعات var paymentVerification = zp.PaymentVerificationAsync(merchantCode, AuthorityQuery, amount); // بررسی وضعیت تایید پرداخت if (paymentVerification.Result.Body.Status == 100) { refId = paymentVerification.Result.Body.RefID; // پرداخت موفق بوده و اطلاعات دریافتی را در دیتابیس ثبت می کنیم // در این قسمت می توانید اطلاعات دریافتی را در دیتابیس ذخیره کنید Payment payment = _context.Payment.Find(paymentId); if (payment != null) { payment.ReferenceNumber = refId; payment.SaleReferenceId = AuthorityQuery.ToString(); payment.StatusPayment = Convert.ToString(paymentVerification.Result.Body.Status); _context.Update(payment); //بعد از ثبت موفقیت آمیز فرآیند پرداخت //سبد خرید را خالی کرده var Cart = new ShoppingCart(_contextAccessor, _context); var items = _context.CartItems.Include(c => c.Product).Where(current => current.CartId == Cart.GetCart(_contextAccessor)); // clear ShoppingCart _context.CartItems.RemoveRange(items); // شماره آی دی جدول کاربر var userId = _contextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; //آخرین سفارش کاربر را گرفته و مهر تائید بر آن می زنیم Order order = _context.Order.Where(c => c.UserId == userId).OrderByDescending(d => d.OrderDate).FirstOrDefault(); //مهر تائید order.IsBuy = true; _context.Update(order); _context.SaveChanges(); } ViewBag.SaleID = saleOrderId; ViewBag.PaymentID = paymentId; ViewBag.Message = ZarinPalResult.Status(paymentVerification.Result.Body.Status.ToString()); ViewBag.SaleReferenceId = refId; //ViewBag.Image = "~/Content/Images/accept.png"; } else { Payment payment = _context.Payment.Find(paymentId); if (payment != null) { payment.ReferenceNumber = 0; payment.SaleReferenceId = AuthorityQuery.ToString(); payment.StatusPayment = Convert.ToString(paymentVerification.Result.Body.Status); _context.Update(payment); _context.SaveChanges(); } ViewBag.SaleID = saleOrderId; ViewBag.PaymentID = paymentId; ViewBag.Message = ZarinPalResult.Status(Convert.ToString(paymentVerification.Result.Body.Status)); ViewBag.SaleReferenceId = "**************"; //ViewBag.Image = "~/Content/Images/notaccept.png"; } } else { int paymentId = Convert.ToInt32(saleOrderId); Payment payment = _context.Payment.Find(paymentId); if (payment != null) { payment.ReferenceNumber = 0; payment.SaleReferenceId = AuthorityQuery.ToString(); payment.StatusPayment = StatusQuery.ToString(); _context.Update(payment); _context.SaveChanges(); } ViewBag.PaymentID = paymentId; ViewBag.Message = StatusQuery.ToString(); ViewBag.SaleReferenceId = "**************"; //ViewBag.Image = "~/Content/Images/notaccept.png"; } } else { ViewBag.Message = "دسترسی امکانپذیر نیست"; } } catch { ViewBag.Message = "پاسخی دریافت نشد"; } return(View()); }
public void ConnectTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromMinutes(-10); }); }
public void SslProtocols_SetUsingUnsupported_Throws(SslProtocols protocol) { var handler = new WinHttpHandler(); Assert.Throws <NotSupportedException>(() => { handler.SslProtocols = protocol; }); }
public void ConnectTimeout_SetInfiniteValue_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.ConnectTimeout = Timeout.InfiniteTimeSpan; }
public void SslProtocols_SetUsingSupported_Success(SslProtocols protocol) { var handler = new WinHttpHandler(); handler.SslProtocols = protocol; }
public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; }); }
public void SslProtocols_SetUsingNone_Throws() { var handler = new WinHttpHandler(); Assert.Throws <NotSupportedException>(() => { handler.SslProtocols = SslProtocols.None; }); }
public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; }
public void SslProtocols_SetUsingInvalidEnum_Throws() { var handler = new WinHttpHandler(); Assert.Throws <NotSupportedException>(() => { handler.SslProtocols = (SslProtocols)4096; }); }
public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown() { var handler = new WinHttpHandler(); handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer; }
public void SecureRequest_ClientCertificateOptionAutomatic_CertStoreEmpty_NullCertificateContextSet() { using (var handler = new WinHttpHandler()) { handler.ClientCertificateOption = ClientCertificateOption.Automatic; using (HttpResponseMessage response = SendRequestHelper.Send( handler, () => { }, TestServer.FakeSecureServerEndpoint)) { Assert.Equal(1, APICallHistory.WinHttpOptionClientCertContext.Count); Assert.Equal(IntPtr.Zero, APICallHistory.WinHttpOptionClientCertContext[0]); } } }
public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException() { var handler = new WinHttpHandler(); Assert.Throws <ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = -1; }); }
public void SecureRequest_ClientCertificateOptionAutomatic_CertStoreHasValidAndInvalidCerts_ValidCertificateContextSet() { using (var handler = new WinHttpHandler()) { var helper = new ClientCertificateHelper(); TestControl.CurrentUserCertificateStore = helper.ValidAndInvalidClientCertificateCollection; handler.ClientCertificateOption = ClientCertificateOption.Automatic; using (HttpResponseMessage response = SendRequestHelper.Send( handler, () => { }, TestServer.FakeSecureServerEndpoint)) { Assert.Equal(1, APICallHistory.WinHttpOptionClientCertContext.Count); Assert.NotEqual(IntPtr.Zero, APICallHistory.WinHttpOptionClientCertContext[0]); } } }
public void MaxConnectionsPerServer_SetPositiveValue_Success() { var handler = new WinHttpHandler(); handler.MaxConnectionsPerServer = 1; }
private HttpResponseMessage SendRequestHelper(WinHttpHandler handler, Action setup) { return(SendRequestHelper(handler, setup, FakeServerEndpoint)); }