Exemplo n.º 1
0
        /// <summary>
        /// HTTPs the client request response synchronize.
        /// </summary>
        /// <typeparam name="T">T object</typeparam>
        /// <param name="value">The value.</param>
        /// <param name="uri">The URI.</param>
        /// <returns>return T object</returns>
        public static T HttpClientRequestReponceSync <T>(T value, string uri)
        {
            var signingHandler = new HmacSigningHandler(new DummySecretRepository(), new CanonicalRepresentationBuilder(), new HmacSignatureCalculator());

            signingHandler.Username = Security.Encrypt("username" + "###" + DateTime.UtcNow);

            var client = new HttpClient(new RequestContentMd5SyncHandler()
            {
                InnerHandler = signingHandler
            });

            client.BaseAddress = new Uri(ProjectConfiguration.WebApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var httpresult = client.GetAsync(uri).Result;

            if (httpresult.IsSuccessStatusCode)
            {
                var result = httpresult.Content.ReadAsAsync <T>();
                return((T)Convert.ChangeType(result.Result, typeof(T)));
            }

            return(default(T));
        }
        public void Initialize(WebApiProviderDescriptor providerDescriptor)
        {
            this.providerDescriptor = providerDescriptor;
            baseUrl = this.providerDescriptor.Data["Url"];
            if (!baseUrl.EndsWith("/"))
            {
                baseUrl = baseUrl + "/";
            }

            var signingHandler = new HmacSigningHandler(
                this.providerDescriptor.Data["ApiKey"],
                this.providerDescriptor.Data["SecretKey"],
                new CanonicalRepresentationBuilder(),
                new HmacSignatureCalculator());

            client = new HttpClient(
                new AddUserAgentHandler
            {
                InnerHandler =
                    new RequestContentMd5Handler
                {
                    InnerHandler = signingHandler
                }
            });
        }
Exemplo n.º 3
0
        /// <summary>
        /// HTTPs the client post pass entity return entity.
        /// </summary>
        /// <typeparam name="O">O object</typeparam>
        /// <typeparam name="I">I object</typeparam>
        /// <param name="value">The value.</param>
        /// <param name="uri">The URI.</param>
        /// <returns>Return T Object</returns>
        public static async Task <O> HttpClientPostPassEntityReturnEntity <O, I>(I value, string uri)
        {
            var signingHandler = new HmacSigningHandler(new DummySecretRepository(), new CanonicalRepresentationBuilder(), new HmacSignatureCalculator());

            signingHandler.Username = Security.Encrypt("username" + "###" + DateTime.UtcNow);

            var client = new HttpClient(new RequestContentMd5Handler()
            {
                InnerHandler = signingHandler
            });

            client.BaseAddress = new Uri(ProjectConfiguration.WebApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.PostAsJsonAsync(uri, value);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync <O>();

                return((O)Convert.ChangeType(result, typeof(O)));
            }

            return(default(O));
        }
Exemplo n.º 4
0
        protected virtual WebApplicationFactory <Startup> CreateFactory()
        {
            var f = new WebApplicationFactory <Startup>()
                    .WithWebHostBuilder(builder => builder.UseContentRoot("."));
            //{
            //    Environment = TestEnvironment
            //};

            var secretRepository = new SecretStore();

            secretRepository.Assign("1234", "ABCD");

            var mrb        = new HmacMessageRepresentationBuilder();
            var calculator = new HmacSignatureCalculator();

            HmacClient = new HmacClient
            {
                ClientId = "1234"
            };
            var hmacHandler = new HmacClientHandler(HmacClient);
            var requestContentMd5Handler = new RequestContentMd5Handler();
            var hmacSigningHandler       = new HmacSigningHandler(secretRepository, mrb, calculator);

            // Inject all the handlers in the correct order
            Client = f.CreateDefaultClient(hmacHandler, requestContentMd5Handler, hmacSigningHandler);

            //Startup = Program.Startup;

            return(f);
        }
Exemplo n.º 5
0
        public static void Run()
        {
            var signingHandler = new HmacSigningHandler(new ClientSecretRepository(Constant.APP_KEY, Constant.APP_SECRET),
                                                        new ClientCanonicalRepresentationBuilder(), new HmacSignatureCalculator());

            // signingHandler.AppKey = Constant.APP_KEY;
            UploadFiles(signingHandler);
        }
Exemplo n.º 6
0
        private static async void UploadFiles(HmacSigningHandler signingHandler)
        {
            Uri        server     = new Uri("http://*****:*****@"..\..\TestData\HintDesk.png", FileMode.Open, FileAccess.Read, FileShare.Read));
            MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent();

            multipartFormDataContent.Add(stringContent, "Broken Sword", "Broken Sword.txt");
            multipartFormDataContent.Add(streamConent, "HintDesk", "HintDesk.png");

            //HttpResponseMessage responseMessage = await httpClient.PostAsync(server, multipartFormDataContent);
            HttpResponseMessage responseMessage = httpClient.PostAsync(server, multipartFormDataContent).Result;

            if (responseMessage.IsSuccessStatusCode)
            {
                Console.WriteLine("上传成功");
                IList <HDFile> hdFiles = await responseMessage.Content.ReadAsAsync <IList <HDFile> >();

                if (Directory.Exists(DownloadFolder))
                {
                    (new DirectoryInfo(DownloadFolder)).Empty();
                }
                else
                {
                    Directory.CreateDirectory(DownloadFolder);
                }

                foreach (HDFile hdFile in hdFiles)
                {
                    responseMessage = httpClient.GetAsync(new Uri(hdFile.Url)).Result;

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        using (FileStream fs = File.Create(Path.Combine(DownloadFolder, hdFile.Name)))
                        {
                            Stream streamFromService = await responseMessage.Content.ReadAsStreamAsync();

                            streamFromService.CopyTo(fs);
                        }
                    }
                }

                Console.WriteLine("下载完成");
            }
            else
            {
                Console.WriteLine("上传文件发生错误");
            }
        }
Exemplo n.º 7
0
        public void Setup()
        {
            secretRepository      = new Mock <ISecretRepository>(MockBehavior.Strict);
            representationBuilder = new Mock <IMessageRepresentationBuilder>(MockBehavior.Strict);
            calculator            = new Mock <ISignatureCalculator>(MockBehavior.Strict);

            handler = new HmacSigningHandler(secretRepository.Object, representationBuilder.Object, calculator.Object, "SHA256")
            {
                InnerHandler = new StubResponseHandler()
            };
        }
Exemplo n.º 8
0
        private static void GetProduct(HmacSigningHandler signingHandler)
        {
            Console.WriteLine("\r\n\r\nGet The Product Of Location 1 http://localhost:4779/api/products/1");
            var getClient = new HttpClient(new RequestContentMd5Handler()
            {
                InnerHandler = signingHandler
            });

            var getResponse = getClient.GetStringAsync("http://localhost:4779/api/products/1");
            var getResult   = getResponse.Result;

            Console.WriteLine("Server response: " + getResult);
        }
Exemplo n.º 9
0
        public static void GetSelfDefineRouteResult(HmacSigningHandler signingHandler)
        {
            Console.WriteLine("\r\n\r\nGet http://localhost:4779/api/users/Admin/products");
            var getClient = new HttpClient(new RequestContentMd5Handler()
            {
                InnerHandler = signingHandler
            });

            var getResponse = getClient.GetStringAsync("http://localhost:4779/api/users/Admin/products");
            var getResult   = getResponse.Result;

            Console.WriteLine("Server response: " + getResult);
        }
Exemplo n.º 10
0
        public static void GetOrderById(HmacSigningHandler signingHandler)
        {
            Console.WriteLine("\r\n\r\nGet http://localhost:4779/api/orders/2");
            var getClient = new HttpClient(new RequestContentMd5Handler()
            {
                InnerHandler = signingHandler
            });

            var getResponse = getClient.GetStringAsync("http://localhost:4779/api/orders/2");
            var getResult   = getResponse.Result;

            Console.WriteLine("Server response: " + getResult);
        }
Exemplo n.º 11
0
        public static void Run()
        {
            Console.WriteLine("WebApi Client Test开始.....\r\n");
            var signingHandler = new HmacSigningHandler(new ClientSecretRepository(Constant.APP_KEY, Constant.APP_SECRET), new ClientCanonicalRepresentationBuilder(),
                                                        new HmacSignatureCalculator());

            //signingHandler.AppKey = Constant.APP_KEY;

            // GetProducts(signingHandler);
            //GetProduct(signingHandler);
            // AddProduct(signingHandler);

            //GetSelfDefineRouteResult(signingHandler);
            //GetOrder(signingHandler);
            GetOrderById(signingHandler);

            Console.WriteLine("\r\nWebApi Client Test结束.....\r\n");
        }
Exemplo n.º 12
0
        private static void AddProduct(HmacSigningHandler signingHandler)
        {
            Console.WriteLine("Post Add Product http://localhost:4779/api/products");

            var client = new HttpClient(new RequestContentMd5Handler()
            {
                InnerHandler = signingHandler
            });
            Product product = new Product()
            {
                Id = 5, Name = "Apple", Category = "Fruit", Price = 12.11m
            };
            //var productJson = JsonConvert.SerializeObject(product);
            var response = client.PostAsJsonAsync("http://localhost:4779/api/products", product).Result;
            var result   = response.Content.ReadAsStringAsync().Result;

            // var result = response.Content.ReadAsAsync<string>().Result;

            Console.WriteLine("Server response: " + result);
        }
Exemplo n.º 13
0
        public void SetUp()
        {
            mockBuildRequestSignature = new Mock <IBuildRequestSignature>();

            mockBuildRequestSignature.Setup(x => x.Build("secret", It.IsAny <HttpRequestMessage>()))
            .Returns("signature");

            var handler = new HmacSigningHandler("secret", mockBuildRequestSignature.Object)
            {
                InnerHandler = new TestHandler()
            };

            client = new HttpClient(handler);

            request = new HttpRequestMessage(HttpMethod.Get, "http://www.test.com")
            {
                Content = new StringContent("something")
            };
            request.Headers.Date = new DateTimeOffset(DateTime.Now, DateTime.Now - DateTime.UtcNow);
        }
Exemplo n.º 14
0
        /// <summary>
        /// HTTPs the client post.
        /// </summary>
        /// <typeparam name="T">T object</typeparam>
        /// <param name="value">The value.</param>
        /// <param name="uri">The URI.</param>
        /// <returns>Return T object</returns>
        public static async Task <string> HttpClientPost <T>(T value, string uri)
        {
            var signingHandler = new HmacSigningHandler(new DummySecretRepository(), new CanonicalRepresentationBuilder(), new HmacSignatureCalculator());

            signingHandler.Username = Security.Encrypt("username" + "###" + DateTime.UtcNow);
            var client = new HttpClient(new RequestContentMd5Handler()
            {
                InnerHandler = signingHandler
            });

            client.BaseAddress = new Uri(ProjectConfiguration.WebApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.PostAsJsonAsync(uri, value);

            if (response.IsSuccessStatusCode)
            {
                return(string.Empty);
            }

            return(response.StatusCode.ToString());
        }