private static async Task<RequestResponse> ProcessRequest(EasypayConfig config, string data, HttpMethod httpMethod, string path, string reqId)
        {
            var contentType = httpMethod.Method == "GET" ? "" : "application/vnd.ch.swisscom.easypay.direct.payment+json";
            var url = new Uri("https://" + config.Host + config.Basepath + path);
            var now = DateTime.Now;
            var date = now.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.GetCultureInfoByIetfLanguageTag("en")) + " +0000"; //Mon, 07 Dec 2015 09:01:30 +0000

            var client = new HttpClient();
            var request = new HttpRequestMessage(httpMethod, url);
            request.Headers.Add("X-SCS-Date", date);
            request.Headers.Add("X-Request-Id", reqId);
            request.Headers.Add("X-Merchant-Id", config.MerchantId);
            request.Headers.Add("X-CE-Client-Specification-Version", "1.1");

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.ch.swisscom.easypay.message.list+json"));
            request.Headers.Date = now;

            var md5Hash = data != null ? Signature.HashData(Encoding.UTF8.GetBytes(data)) : null;
            var hashString = Signature.CreateHashString(httpMethod.Method, md5Hash != null ? Convert.ToBase64String(md5Hash) : "", contentType, date, path);
            var signature = Signature.Sign(Encoding.UTF8.GetBytes(config.EasypaySecret), Encoding.UTF8.GetBytes(hashString));
            
            request.Headers.Add("X-SCS-Signature", Convert.ToBase64String(signature));

            if (data != null)
            {
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                request.Content = new StringContent(data);
                request.Content.Headers.ContentMD5 = md5Hash;
            }

            var result = await client.SendAsync(request);
            var ret = new RequestResponse {Response = await result.Content.ReadAsStringAsync(), StatusCode = result.StatusCode};
            return ret;
        }
Esempio n. 2
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 /// <param name="consumerKey"></param>
 /// <param name="consumerSecret"></param>        
 public OAuthGenerator(string consumerKey, string consumerSecret)
 {
     this.queryParameters = new ArrayList();
     this.consumerKey = consumerKey;
     this.consumerSecret = System.Text.Encoding.ASCII.GetBytes(consumerSecret);
     this.methodHttp = HttpMethod.POST;
 }
Esempio n. 3
0
        public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null)
        {
            _buffer = new byte[8192];
            _bufferIndex = 0;
            _read = 0;
            _responseType = ResponseType.Unknown;
            _uri = uri;
            IPAddress ip;
            var headersString = string.Empty;
            var contentLength = data != null ? data.Length : 0;

            if (headers != null && headers.Any())
                headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim()));

            if (_uri.HostNameType == UriHostNameType.Dns)
            {
                var host = Dns.GetHostEntry(_uri.Host);
                ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork);
            }
            else
            {
                ip = IPAddress.Parse(_uri.Host);
            }

            _endPoint = new IPEndPoint(ip, _uri.Port);
            _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n");

            if (data == null)
                return;

            var tmpRequest = new byte[_request.Length + data.Length];
            Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length);
            Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length);
            _request = tmpRequest;
        }
Esempio n. 4
0
        public static string BuildBase64Signature(
                string apiKey,
                string appId,
                Uri rawUri,
                HttpMethod httpMethod,
                HttpContent content,
                string nonce,
                string requestTimeStamp
            )
        {
            var requestUri = HttpUtility.UrlEncode(rawUri.AbsoluteUri.ToLower());
            var requestHttpMethod = httpMethod.Method;

            // Get the content string out of the content.
            string requestContentBase64String = ComputeBase64RequestContent(content);

            // Rebuild the signature raw data.
            var signatureRawData =
            $"{appId}{requestHttpMethod}{requestUri}{requestTimeStamp}{nonce}{requestContentBase64String}";

            // Get the api key bytes.
            var secretKeyBytes = Convert.FromBase64String(apiKey);

            // Get the signature.
            var signature = Encoding.UTF8.GetBytes(signatureRawData);

            // Create HMAC SHA class with key data.
            using (var hmac = new HMACSHA256(secretKeyBytes))
            {
                return Convert.ToBase64String(hmac.ComputeHash(signature));
            }
        }
Esempio n. 5
0
 private Request(string url, HttpMethod httpMethod, string entity = null)
 {
     _url = url;
     _httpMethod = httpMethod;
     _entity = entity;
     _webRequest = CreateWebRequest(_url, _entity, _httpMethod);
 }
 public WebRequest MakeHttpRequest(Uri request, HttpMethod httpMethod)
 {
     return this.consumer.CreateHttpRequest(
         request.AbsoluteUri,
         httpMethod,
         new UriBuilder(request).GetQueryParams().ToArray());
 }
        public async Task<HttpResponseMessage> Send(HttpMethod method, Uri uri, IDictionary<string, string> requestHeaders, object content)
        {
            requestHeaders = requestHeaders ?? new Dictionary<string, string>() { };

            var httpRequestMessage = new HttpRequestMessage(method, uri)
            {
                Content = GetContent(content, requestHeaders),
            };

            foreach (var header in DefaultRequestHeaders)
            {
                if (requestHeaders.Any(x => x.Key == header.Key))
                    requestHeaders.Remove(header.Key);

                requestHeaders.Add(header.Key, header.Value);
            }

            foreach (var header in requestHeaders)
            {
                if (httpRequestMessage.Headers.Contains(header.Key))
                    httpRequestMessage.Headers.Remove(header.Key);

                httpRequestMessage.Headers.Add(header.Key, header.Value);
            }

            return await _httpClient.SendAsync(httpRequestMessage);
        }
Esempio n. 8
0
 /// <summary>
 /// Initializes SteamRequest with a resource constructed via the Steam Interface, Steam API Method, and Steam API Version
 /// </summary>
 /// <param name="steamInterface">Steam API Interface to access (i.e. ISteamNews)</param>
 /// <param name="steamApi">Method within the Steam API to use (i.e. GetNewsForApp)</param>
 /// <param name="version">Version of the API being requested (i.e. v0001)</param>
 /// <param name="method">HTTP Method to use for this request</param>
 public SteamRequest( SteamAPIInterface steamInterface, string steamApi, SteamMethodVersion version, HttpMethod method )
     : this(( Enum.GetName( typeof( SteamAPIInterface ), steamInterface ) + "/" + steamApi + "/" + Enum.GetName( typeof( SteamMethodVersion ), version ) ), method)
 {
     SteamInterface = steamInterface;
     SteamApiMethod = steamApi;
     SteamMethodVersion = version;
 }
        /// <summary>
        /// Creates the web request.
        /// </summary>
        /// <param name="uri">The request Uri.</param>
        /// <param name="timeout">The timeout.</param>
        /// <param name="builder">The builder.</param>
        /// <returns>A web request for performing the operation.</returns>
        internal static StorageRequestMessage CreateRequestMessage(HttpMethod method, Uri uri, int? timeout, UriQueryBuilder builder, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (builder == null)
            {
                builder = new UriQueryBuilder();
            }

            if (timeout.HasValue && timeout.Value > 0)
            {
                builder.Add("timeout", timeout.ToString());
            }

#if WINDOWS_RT && !NETCORE
            // Windows Phone does not allow the caller to disable caching, so a random GUID
            // is added to every URI to make it look like a different request.
            builder.Add("randomguid", Guid.NewGuid().ToString("N"));
#endif

            Uri uriRequest = builder.AddToUri(uri);

            StorageRequestMessage msg = new StorageRequestMessage(method, uriRequest, canonicalizer, credentials, credentials.AccountName);
            msg.Content = content;

            return msg;
        }
Esempio n. 10
0
		public RestClient(string endpoint = "", HttpMethod method = HttpMethod.GET, string postData = "")
		{
			EndPoint = endpoint;
			Method = method;
			ContentType = "application/json";
			PostData = postData;
		}
Esempio n. 11
0
        static string GenerateSignature(string consumerSecret, Uri uri, HttpMethod method, Token token, IEnumerable<KeyValuePair<string, string>> parameters)
        {
            if (ComputeHash == null)
            {
                throw new InvalidOperationException("ComputeHash is null, must initialize before call OAuthUtility.HashFunction = /* your computeHash code */ at once.");
            }

            var hmacKeyBase = consumerSecret.UrlEncode() + "&" + ((token == null) ? "" : token.Secret).UrlEncode();

            // escaped => unescaped[]
            var queryParams = Utility.ParseQueryString(uri.GetComponents(UriComponents.Query | UriComponents.KeepDelimiter, UriFormat.UriEscaped));

            var stringParameter = parameters
                .Where(x => x.Key.ToLower() != "realm")
                .Concat(queryParams)
                .Select(p => new { Key = p.Key.UrlEncode(), Value = p.Value.UrlEncode() })
                .OrderBy(p => p.Key, StringComparer.Ordinal)
                .ThenBy(p => p.Value, StringComparer.Ordinal)
                .Select(p => p.Key + "=" + p.Value)
                .ToString("&");
            var signatureBase = method.ToString() +
                "&" + uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped).UrlEncode() +
                "&" + stringParameter.UrlEncode();

            var hash = ComputeHash(Encoding.UTF8.GetBytes(hmacKeyBase), Encoding.UTF8.GetBytes(signatureBase));
            return Convert.ToBase64String(hash).UrlEncode();
        }
Esempio n. 12
0
 /// <summary>
 /// Creates a <see cref="RequestMatcher"/> that expect the given request <see cref="HttpMethod"/>.
 /// </summary>
 /// <param name="method">The HTTP method.</param>
 /// <returns>The request matcher.</returns>
 public static RequestMatcher MatchMethod(HttpMethod method)
 {
     return delegate(IClientHttpRequest request)
     {
         AssertionUtils.AreEqual(method, request.Method, "Unexpected HTTP method");
     };
 }
    	/// <summary>
        /// Handles the error in the given response. 
        /// <para/>
        /// This method is only called when HasError() method has returned <see langword="true"/>.
        /// </summary>
        /// <remarks>
        /// This implementation throws appropriate exception if the response status code 
        /// is a client code error (4xx) or a server code error (5xx). 
        /// </remarks>
        /// <param name="requestUri">The request URI.</param>
        /// <param name="requestMethod">The request method.</param>
        /// <param name="response">The response message with the error.</param>
        public override void HandleError(Uri requestUri, HttpMethod requestMethod, HttpResponseMessage<byte[]> response)
        {
			if (response == null) throw new ArgumentNullException("response");

            var type = (int)response.StatusCode / 100;
            switch (type)
            {
            	case 4:
            		HandleClientErrors(response);
            		break;
            	case 5:
            		HandleServerErrors(response.StatusCode);
            		break;
            }

            // if not otherwise handled, do default handling and wrap with StackExchangeApiException
            try
            {
                base.HandleError(requestUri, requestMethod, response);
            }
            catch (Exception ex)
            {
                throw new StackExchangeApiException("Error consuming StackExchange REST API.", ex);
            }
        }
Esempio n. 14
0
 public CurlRequest(HttpMethod method, string url, string cookies = null, string referer = null)
 {
     Method = method;
     Url = url;
     Cookies = cookies;
     Referer = referer;
 }
Esempio n. 15
0
        private async Task<string> CallAzureMLSM(HttpMethod method, string url, string payload)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.accessContext.WorkspaceAccessToken);

                HttpRequestMessage req = new HttpRequestMessage(method, url);

                if (!string.IsNullOrWhiteSpace(payload))
                {
                    req.Content = new StringContent(payload);
                    req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }

                HttpResponseMessage response = await client.SendAsync(req);
                string result = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return result;
                }
                else
                {
                    throw new HttpRequestException(string.Format("{0}\n{1}", result, response.StatusCode));
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Asynchronously downloads a string from the specified url.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="method">The method.</param>
        /// <param name="acceptEncoded">if set to <c>true</c> accept encoded response.</param>
        /// <param name="postdata">The post data.</param>
        /// <param name="dataCompression">The post data compression method.</param>
        public static async Task<DownloadResult<String>> DownloadStringAsync(Uri url, HttpMethod method = null, bool acceptEncoded = false,
            string postdata = null, DataCompression dataCompression = DataCompression.None)
        {
            string urlValidationError;
            if (!IsValidURL(url, out urlValidationError))
                throw new ArgumentException(urlValidationError);

            HttpPostData postData = String.IsNullOrWhiteSpace(postdata) ? null : new HttpPostData(postdata, dataCompression);
            HttpClientServiceRequest request = new HttpClientServiceRequest();
            try
            {
                HttpResponseMessage response =
                    await request.SendAsync(url, method, postData, dataCompression, acceptEncoded, StringAccept).ConfigureAwait(false);

                using (response)
                {
                    Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
                    return GetString(request.BaseUrl, stream);
                }
            }
            catch (HttpWebClientServiceException ex)
            {
                return new DownloadResult<String>(String.Empty, ex);
            }
        }
Esempio n. 17
0
        public string Request(string url, HttpRequestParameter parameter, HttpMethod method, HttpHeader headers)
        {
            string _params = string.Empty;

            if (parameter != null && parameter.Count > 0)
            {
                _params = parameter.ToString();
            }

            if (method == HttpMethod.GET)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + _params;
                }
                else
                {
                    url = url + "?" + _params;
                }

                return HttpGet(url, headers);
            }
            else
            {
                return HttpPost(url, _params, headers);
            }
        }
Esempio n. 18
0
        private static HttpRequestMessage CreateJsonRequest(string url, HttpMethod method)
        {
            var request = new HttpRequestMessage(method, url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return request;
        }
Esempio n. 19
0
 /// <summary>
 /// Webs the request.
 /// </summary>
 /// <param name="method">The method.</param>
 /// <param name="url">The URL.</param>
 /// <param name="postData">The post data.</param>
 /// <returns></returns>
 public string WebRequest(HttpMethod method, string url, string postData)
 {
     this.Message = string.Empty;
     HttpWebRequest webRequest = null;
     StreamWriter requestWriter = null;
     string responseData = "";
     webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
     webRequest.Method = method.ToString();
     webRequest.ServicePoint.Expect100Continue = false;
     if (method == HttpMethod.POST)
     {
         webRequest.ContentType = "application/x-www-form-urlencoded";
         requestWriter = new StreamWriter(webRequest.GetRequestStream());
         try
         {
             requestWriter.Write(postData);
         }
         catch (Exception ex)
         {
             this.Message = ex.Message;
         }
         finally
         {
             requestWriter.Close();
             requestWriter = null;
         }
     }
     responseData = GetWebResponse(webRequest);
     webRequest = null;
     return responseData;
 }
 internal static HttpRequestMessage CreateTestMessage(string url, HttpMethod httpMethod, HttpConfiguration config)
 {
     HttpRequestMessage requestMessage = new HttpRequestMessage(httpMethod, url);
     IHttpRouteData rd = config.Routes[0].GetRouteData("/", requestMessage);
     requestMessage.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, rd);
     return requestMessage;
 }
Esempio n. 21
0
        /// <summary>
        /// Asserts that the API route exists, has the specified Http method and meets the expectations
        /// </summary>
        public static void HasApiRoute(HttpConfiguration config, string url, HttpMethod httpMethod, object expectations)
        {
            var propertyReader = new PropertyReader();
            var expectedProps = propertyReader.Properties(expectations);

            HasApiRoute(config, url, httpMethod, expectedProps);
        }
		public RequestData(HttpMethod method, string path, PostData<object> data, IConnectionConfigurationValues global, IRequestConfiguration local, IMemoryStreamFactory memoryStreamFactory)
		{
			this.ConnectionSettings = global;
			this.MemoryStreamFactory = memoryStreamFactory;
			this.Method = method;
			this.PostData = data;
			this.Path = this.CreatePathWithQueryStrings(path, this.ConnectionSettings, null);

			this.Pipelined = global.HttpPipeliningEnabled || (local?.EnableHttpPipelining).GetValueOrDefault(false);
			this.HttpCompression = global.EnableHttpCompression;
			this.ContentType = local?.ContentType ?? MimeType;
			this.Headers = global.Headers;

			this.RequestTimeout = local?.RequestTimeout ?? global.RequestTimeout;
			this.PingTimeout = 
				local?.PingTimeout
				?? global?.PingTimeout
				?? (global.ConnectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);

			this.KeepAliveInterval = (int)(global.KeepAliveInterval?.TotalMilliseconds ?? 2000);
			this.KeepAliveTime = (int)(global.KeepAliveTime?.TotalMilliseconds ?? 2000);

			this.ProxyAddress = global.ProxyAddress;
			this.ProxyUsername = global.ProxyUsername;
			this.ProxyPassword = global.ProxyPassword;
			this.DisableAutomaticProxyDetection = global.DisableAutomaticProxyDetection;
			this.BasicAuthorizationCredentials = local?.BasicAuthenticationCredentials ?? global.BasicAuthenticationCredentials;
			this.CancellationToken = local?.CancellationToken ?? CancellationToken.None;
			this.AllowedStatusCodes = local?.AllowedStatusCodes ?? Enumerable.Empty<int>();
		}
Esempio n. 23
0
 public static BatchStep Add(this IList<BatchStep> list, HttpMethod method, string to, object body)
 {
     var id = list.Count;
     var step = new BatchStep {Method = method, To = to, Body = body, Id = id};
     list.Add(step);
     return step;
 }
Esempio n. 24
0
 protected WebJob()
 {
     Method = HttpMethod.Get;
     formData = new List<KeyValuePair<string, string>>();
     headers = new List<KeyValuePair<string, string>>();
     formString = null;
 }
Esempio n. 25
0
        public static async Task<byte[]> SendODataHttpRequestWithCanary(Uri uri, HttpMethod method, Stream requestContent, string contentType,
            HttpClientHandler clientHandler, SPOAuthUtility authUtility, Dictionary<string, string> headers = null)
        {
            // Make a post request to {siteUri}/_api/contextinfo to get the canary
            var response = await HttpUtility.SendODataJsonRequest(
                new Uri(String.Format("{0}/_api/contextinfo", SPOAuthUtility.Current.SiteUrl)),
                HttpMethod.Post,
                null,
                clientHandler,
                SPOAuthUtility.Current);

            Dictionary<String, IJsonValue> dict = new Dictionary<string, IJsonValue>();
            HttpUtility.ParseJson(JsonObject.Parse(Encoding.UTF8.GetString(response, 0, response.Length)), dict);

            string canary = dict["FormDigestValue"].GetString();

            // Make the OData request passing the canary in the request headers
            return await HttpUtility.SendODataHttpRequest(
                uri,
                method,
                requestContent,
                contentType,
                clientHandler,
                SPOAuthUtility.Current,
                new Dictionary<string, string> { 
                { "X-RequestDigest", canary  } 
                });
        }
        public ITwitterQuery Create(string queryURL, HttpMethod httpMethod)
        {
            var queryURLParameter = new ConstructorNamedParameter("queryURL", queryURL);
            var httpMethodParameter = new ConstructorNamedParameter("httpMethod", httpMethod);

            return _twitterQueryFactory.Create(queryURLParameter, httpMethodParameter);
        }
        public override Response Execute(Uri url, HttpMethod method, Func<HttpWebResponse, bool, Response> responseBuilderCallback, string body, Dictionary<string, string> headers, Dictionary<string, string> queryStringParameters, RequestSettings settings)
        {
            if (settings == null)
                settings = new JsonRequestSettings();

            return base.Execute(url, method, responseBuilderCallback, body, headers, queryStringParameters, settings);
        }
        public override Response Stream(Uri url, HttpMethod method, Func<HttpWebResponse, bool, Response> responseBuilderCallback, Stream contents, int bufferSize, long maxReadLength, Dictionary<string, string> headers, Dictionary<string, string> queryStringParameters, RequestSettings settings, Action<long> progressUpdated)
        {
            if (settings == null)
                settings = new JsonRequestSettings();

            return base.Stream(url, method, responseBuilderCallback, contents, bufferSize, maxReadLength, headers, queryStringParameters, settings, progressUpdated);
        }
 public MockHttpRequest(HttpMethod method, string relativeUrl, NameValueCollection queryParams, string requestBody)
 {
     this.method = method;
     this.relativeUrl = relativeUrl;
     this.queryParams = queryParams;
     this.requestBody = requestBody ?? string.Empty;
 }
Esempio n. 30
0
 public CheckoutExistingRequest(string url, HttpMethod method)
     : base(url, method)
 {
 }
Esempio n. 31
0
        public static async Task <HttpResponseMessage> SendAndReceiveAsHttpMessage(this HttpClient httpClient, HttpMethod httpMethod, string requestUri, object content = null, bool ensureSuccess = true)
        {
            var httpMessage = await httpClient.SendAsync(new HttpRequestMessage
            {
                Method     = httpMethod,
                RequestUri = new Uri(requestUri),
                Content    = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json")
            });

            if (ensureSuccess)
            {
                httpMessage.EnsureSuccessStatusCode();
            }

            return(httpMessage);
        }
Esempio n. 32
0
 public UpdatePaymentMethodRequest(string url, HttpMethod method)
     : base(url, method)
 {
 }
Esempio n. 33
0
        public async Task Can_Post_TodoItem_With_Different_Owner_And_Assignee()
        {
            // Arrange
            var person1 = new Person();
            var person2 = new Person();

            _context.People.Add(person1);
            _context.People.Add(person2);
            _context.SaveChanges();

            var todoItem = _todoItemFaker.Generate();
            var content  = new
            {
                data = new
                {
                    type       = "todo-items",
                    attributes = new Dictionary <string, object>()
                    {
                        { "description", todoItem.Description },
                        { "ordinal", todoItem.Ordinal },
                        { "created-date", todoItem.CreatedDate }
                    },
                    relationships = new
                    {
                        owner = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = person1.Id.ToString()
                            }
                        },
                        assignee = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = person2.Id.ToString()
                            }
                        }
                    }
                }
            };

            var httpMethod = new HttpMethod("POST");
            var route      = $"/api/v1/todo-items";

            var request = new HttpRequestMessage(httpMethod, route);

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // Act
            var response = await _fixture.Client.SendAsync(request);

            // Assert -- response
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            var body = await response.Content.ReadAsStringAsync();

            var document = JsonConvert.DeserializeObject <Document>(body);
            var resultId = int.Parse(document.Data.Id);

            // Assert -- database
            var todoItemResult = await _context.TodoItems.SingleAsync(t => t.Id == resultId);

            Assert.Equal(person1.Id, todoItemResult.OwnerId);
            Assert.Equal(person2.Id, todoItemResult.AssigneeId);
        }
Esempio n. 34
0
 public HttpPostContentBinder(HttpMethod httpMethod, IModelSerializer modelSerializer)
     : base(httpMethod, modelSerializer)
 {
 }
 /// <summary>
 /// Create a <see cref="RequestMessage"/>
 /// </summary>
 /// <param name="method">The http method</param>
 /// <param name="requestUri">The requested URI</param>
 public RequestMessage(HttpMethod method, Uri requestUri)
 {
     this.Method     = method;
     this.RequestUri = requestUri;
 }
Esempio n. 36
0
 public LinkDto(string?href, string rel, HttpMethod method)
 {
     Href   = href ?? throw new ArgumentException($"Link href cannot be null for new {nameof(LinkDto)} instance");
     Rel    = rel;
     Method = method;
 }
Esempio n. 37
0
 /// <summary>
 /// Execute the request (more likely request with no body like GET or Delete)
 /// </summary>
 /// <typeparam name="TResult"></typeparam>
 /// <param name="method">The HttpMethod <see cref="HttpMethod"/></param>
 /// <param name="uri">The endpoint URI</param>
 /// <param name="callType">The method Algolia's call type <see cref="CallType"/> </param>
 /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param>
 /// <param name="ct">Optional cancellation token</param>
 public async Task <TResult> ExecuteRequestAsync <TResult>(HttpMethod method, string uri, CallType callType,
                                                           RequestOptions requestOptions = null,
                                                           CancellationToken ct          = default)
     where TResult : class =>
 await ExecuteRequestAsync <TResult, string>(method, uri, callType, requestOptions : requestOptions, ct : ct)
 .ConfigureAwait(false);
Esempio n. 38
0
        protected async Task <TResult> MakeRequestAsync <TParameters, TResult>(HttpMethod method, string url, TParameters parameters)
            where TParameters : ApiParameters
            where TResult : ApiResponse
        {
            ClusterResult response;

            if (settings.LogRequestsAndResponses)
            {
                log.Info("Send {method} request to {serviceName} ({url}) with parameters: {parameters}", method.Method, settings.ServiceName, url, parameters.ToString());
            }

            try
            {
                if (method == HttpMethod.Get)
                {
                    var request = Request.Get(BuildUrl(settings.EndpointUrl + url));
                    var parametersNameValueCollection = parameters.ToNameValueCollection();
                    foreach (var key in parametersNameValueCollection.AllKeys)
                    {
                        request = request.WithAdditionalQueryParameter(key, parametersNameValueCollection[key]);
                    }
                    response = await clusterClient.SendAsync(request).ConfigureAwait(false);
                }
                else if (method == HttpMethod.Post)
                {
                    var serializedPayload = JsonConvert.SerializeObject(parameters, Formatting.Indented);
                    var request           = Request
                                            .Post(BuildUrl(settings.EndpointUrl + url))
                                            .WithContent(serializedPayload, Encoding.UTF8)
                                            .WithContentTypeHeader("application/json");
                    response = await clusterClient.SendAsync(request).ConfigureAwait(false);
                }
                else
                {
                    throw new ApiClientException($"Internal error: unsupported http method: {method.Method}");
                }
            }
            catch (Exception e)
            {
                log.Error(e, "Can't send request to {serviceName}: {message}", settings.ServiceName, e.Message);
                throw new ApiClientException($"Can't send request to {settings.ServiceName}: {e.Message}", e);
            }

            if (response.Status != ClusterResultStatus.Success)
            {
                log.Error("Bad response status from {serviceName}: {status}", settings.ServiceName, response.Status.ToString());
                throw new ApiClientException($"Bad response status from {settings.ServiceName}: {response.Status}");
            }

            if (!response.Response.IsSuccessful)
            {
                log.Error("Bad response code from {serviceName}: {statusCode} {statusCodeDescrption}", settings.ServiceName, (int)response.Response.Code, response.Response.Code.ToString());
                throw new ApiClientException($"Bad response code from {settings.ServiceName}: {(int)response.Response.Code} {response.Response.Code}");
            }

            TResult result;
            string  jsonResult;

            try
            {
                MemoryStream ms = null;
                if (response.Response.HasStream)
                {
                    ms = new MemoryStream();
                    response.Response.Stream.CopyTo(ms);
                }
                else if (response.Response.HasContent)
                {
                    ms = response.Response.Content.ToMemoryStream();
                }
                jsonResult = Encoding.UTF8.GetString(ms.ToArray());
                result     = JsonConvert.DeserializeObject <TResult>(jsonResult);
            }
            catch (Exception e)
            {
                log.Error(e, "Can't parse response from {serviceName}: {message}", settings.ServiceName, e.Message);
                throw new ApiClientException($"Can't parse response from {settings.ServiceName}: {e.Message}", e);
            }

            if (settings.LogRequestsAndResponses)
            {
                var shortened = false;
                var logResult = jsonResult;
                if (jsonResult.Length > 8 * 1024)
                {
                    logResult = result.GetShortLogString();
                    shortened = true;
                }

                log.Info($"Received response from \"{settings.ServiceName}\"{(shortened ? " (сокращенный)" : "")}: {logResult}");
            }

            return(result);
        }
Esempio n. 39
0
 public virtual void OnStartLine(HttpMethod method, HttpVersion version, Span <byte> target, Span <byte> path, Span <byte> query, Span <byte> customMethod, bool pathEncoded)
 {
 }
Esempio n. 40
0
        private static Task <HttpResponseMessage> SendWithHeadersAsync(this HttpClient httpClient, string uri, Dictionary <string, string> headers, HttpMethod method, StringContent content = null)
        {
            var request = new HttpRequestMessage()
            {
                Method     = method,
                RequestUri = new Uri(uri),
            };

            if (content != null)
            {
                request.Content = content;
            }

            foreach (string headerName in headers.Keys)
            {
                request.Headers.Add(headerName, headers[headerName]);
            }

            return(httpClient.SendAsync(request));
        }
Esempio n. 41
0
 public UpdateCardRequest(string url, HttpMethod method)
     : base(url, method)
 {
 }
        async Task <HttpResponseMessage> IHttpClientCallback.SendAndCheckStatus(IHttpClientWrapper clientWrapper, HttpMethod action, string url)
        {
            var requestMessage = CreateRequest(action, url);

            return(await SendRequestAndCheckStatus(clientWrapper, requestMessage));
        }
Esempio n. 43
0
 public CheckoutNewRequest(string url, HttpMethod method)
     : base(url, method)
 {
 }
Esempio n. 44
0
 public RouteAttribute(string route, HttpMethod httpVerb)
 {
     this.Route    = route;
     this.HttpVerb = httpVerb;
 }
Esempio n. 45
0
 public HttpRequestBuilder AddMethod(HttpMethod method)
 {
     this.method = method;
     return(this);
 }
Esempio n. 46
0
 public abstract HttpResponseMessage SendAsync(HttpMethod method, string url);
        async Task <HttpResponseMessage> IHttpClientCallback.SendBodyAndCheckStatus <TRequest>(IHttpClientWrapper clientWrapper, HttpMethod action, TRequest request, string url)
        {
            using (var content = HttpContentConverter.ToJsonStringContent(request))
            {
                var requestMessage = CreateRequest(action, url, content);

                return(await SendRequestAndCheckStatus(clientWrapper, requestMessage));
            }
        }
Esempio n. 48
0
        /// <summary>
        /// Handle Graph user API, support following HTTP methods: GET, POST and PATCH
        /// </summary>
        public async Task <string> SendGraphRequest(string api, string query, string data, HttpMethod method)
        {
            // Set the Graph url. Including: Graph-endpoint/tenat/users?api-version&query
            string url = BuildUrl(api, query);

            return(await SendGraphRequest(method, url, data));
        }
Esempio n. 49
0
        public static Task <HttpResponseMessage> SendJsonAsync <T>(this HttpClient client, HttpMethod method, string url, T value)
        {
            var stream     = new MemoryStream();
            var jsonWriter = new JsonTextWriter(new StreamWriter(stream));

            _jsonSerializer.Serialize(jsonWriter, value);
            jsonWriter.Flush();
            stream.Position = 0;
            var request = new HttpRequestMessage(method, url)
            {
                Content = new StreamContent(stream)
            };

            request.Content.Headers.TryAddWithoutValidation("Content-Type", "application/json");
            return(client.SendAsync(request));
        }
Esempio n. 50
0
        private static HttpWebRequest CreateRequest(string url, HttpMethod httpMethod, RequestSettings requestSettings)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = httpMethod.Method;

            if (requestSettings.TimeoutMs > 0)
            {
                request.Timeout = requestSettings.TimeoutMs;
            }

            if (!string.IsNullOrWhiteSpace(requestSettings.UserAgent))
            {
                request.UserAgent = requestSettings.UserAgent;
            }

            if (requestSettings.Headers.Count > 0)
            {
                var contentType = requestSettings.Headers.Where(x => string.Equals(x.Key, "content-type", StringComparison.OrdinalIgnoreCase))
                                  .FirstOrDefault();

                if (!contentType.Equals(default(KeyValuePair <string, string>)))
                {
                    request.ContentType = contentType.Value;
                }

                foreach (KeyValuePair <string, string> header in requestSettings.Headers
                         .Where(x => !string.Equals(x.Key, "content-type", StringComparison.OrdinalIgnoreCase)))
                {
                    request.Headers[header.Key] = header.Value;
                }
            }

            if (!string.IsNullOrWhiteSpace(requestSettings.Accept))
            {
                request.Accept = requestSettings.Accept;
            }

            request.ContentLength = 0;

            if (!string.IsNullOrWhiteSpace(requestSettings.Body) && !string.Equals(request.Method, "GET",
                                                                                   StringComparison.OrdinalIgnoreCase))
            {
                byte[] bytes = Encoding.UTF8.GetBytes(requestSettings.Body);
                request.ContentLength = bytes.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
            }
            else if (requestSettings.FormData.Count > 0)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(string.Join("&",
                                                                  requestSettings.FormData.Select(x => $"{x.Key}={x.Value}")));
                request.ContentLength = bytes.Length;
                request.ContentType   = "application/x-www-form-urlencoded";
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }
            }
            return(request);
        }
Esempio n. 51
0
        public ApiResult UserQuery(string path, HttpMethod httpMethod, Dictionary <string, string> headers = null, string content = "", bool jsonContent = false)
        {
            xNet.HttpResponse response    = null;
            string            contentType = null;

            path = BaseUri + path;

            if (!(httpMethod == HttpMethod.Get || httpMethod == HttpMethod.Post ||
                  httpMethod == HttpMethod.Delete || httpMethod == HttpMethod.Put))
            {
                throw new ArgumentException("Unsupported http method " + httpMethod);
            }
            if (httpMethod != HttpMethod.Get && content.Length == 0)
            {
                throw new ArgumentException("Empty content.");
            }

            if (headers != null && headers.Count == 0)
            {
                throw new ArgumentException("Empty headers.");
            }

            if (headers != null)
            {
                foreach (var h in headers)
                {
                    _request.AddHeader(h.Key, h.Value);
                }
            }
            if (httpMethod != HttpMethod.Get)
            {
                contentType = jsonContent ? "application/json" : "application/x-www-form-urlencoded";
            }
            lock (_obj)
            {
                try
                {
                    if (httpMethod == HttpMethod.Get)
                    {
                        response = _request.Get(path);
                    }

                    else if (httpMethod == HttpMethod.Post)
                    {
                        response = _request.Post(path, content, contentType);
                    }

                    else if (httpMethod == HttpMethod.Delete)
                    {
                        response = _request.Delete(path, content, contentType);
                    }

                    else if (httpMethod == HttpMethod.Put)
                    {
                        response = _request.Put(path, content, contentType);
                    }
                }
                catch (xNet.HttpException ex)
                {
                    return(new ApiResult((int)ex.HttpStatusCode, ex.InnerMessage));
                }
            }
            content = response.ToString();
            ParseResponseHeaders(response);

            return(new ApiResult((int)response.StatusCode, content));
        }
Esempio n. 52
0
        private async Task ExecuteAsync(
            HttpClient httpClient,
            HttpMethod httpMethod,
            Uri requestUri,
            Func <HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync,
            Func <HttpResponseMessage, bool> isMappedToException,
            Func <HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync,
            IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > errorMappingOverrides,
            CancellationToken cancellationToken)
        {
            IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > mergedErrorMapping =
                MergeErrorMapping(errorMappingOverrides);

            using (var msg = new HttpRequestMessage(httpMethod, requestUri))
            {
                msg.Headers.Add(HttpRequestHeader.Authorization.ToString(), _authenticationHeaderProvider.GetAuthorizationHeader());
                msg.Headers.Add(HttpRequestHeader.UserAgent.ToString(), Utils.GetClientVersion());

                if (modifyRequestMessageAsync != null)
                {
                    await modifyRequestMessageAsync(msg, cancellationToken).ConfigureAwait(false);
                }

                // TODO: pradeepc - find out the list of exceptions that HttpClient can throw.
                HttpResponseMessage responseMsg;
                try
                {
                    responseMsg = await httpClient.SendAsync(msg, cancellationToken).ConfigureAwait(false);

                    if (responseMsg == null)
                    {
                        throw new InvalidOperationException("The response message was null when executing operation {0}.".FormatInvariant(httpMethod));
                    }

                    if (!isMappedToException(responseMsg))
                    {
                        if (processResponseMessageAsync != null)
                        {
                            await processResponseMessageAsync(responseMsg, cancellationToken).ConfigureAwait(false);
                        }
                    }
                }
                catch (AggregateException ex)
                {
                    var innerExceptions = ex.Flatten().InnerExceptions;
                    if (innerExceptions.Any(Fx.IsFatal))
                    {
                        throw;
                    }

                    // Apparently HttpClient throws AggregateException when a timeout occurs.
                    // TODO: pradeepc - need to confirm this with ASP.NET team
                    if (innerExceptions.Any(e => e is TimeoutException))
                    {
                        throw new IotHubCommunicationException(ex.Message, ex);
                    }

                    throw new IotHubException(ex.Message, ex);
                }
                catch (TimeoutException ex)
                {
                    throw new IotHubCommunicationException(ex.Message, ex);
                }
                catch (IOException ex)
                {
                    throw new IotHubCommunicationException(ex.Message, ex);
                }
                catch (HttpRequestException ex)
                {
                    throw new IotHubCommunicationException(ex.Message, ex);
                }
                catch (TaskCanceledException ex)
                {
                    // Unfortunately TaskCanceledException is thrown when HttpClient times out.
                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw new IotHubException(ex.Message, ex);
                    }

                    throw new IotHubCommunicationException(string.Format(CultureInfo.InvariantCulture, "The {0} operation timed out.", httpMethod), ex);
                }
                catch (Exception ex)
                {
                    if (Fx.IsFatal(ex))
                    {
                        throw;
                    }

                    throw new IotHubException(ex.Message, ex);
                }

                if (isMappedToException(responseMsg))
                {
                    Exception mappedEx = await MapToExceptionAsync(responseMsg, mergedErrorMapping).ConfigureAwait(false);

                    throw mappedEx;
                }
            }
        }
Esempio n. 53
0
    public static async Task <HttpResponseMessage> CreateNewAsync(Stream responseStream, HttpMethod requestMethod, CancellationToken cancellationToken = default)
    {
        // https://tools.ietf.org/html/rfc7230#section-3
        // The normal procedure for parsing an HTTP message is to read the
        // start - line into a structure, read each header field into a hash table
        // by field name until the empty line, and then use the parsed data to
        // determine if a message body is expected.If a message body has been
        // indicated, then it is read as a stream until an amount of octets
        // equal to the message body length is read or the connection is closed.

        // https://tools.ietf.org/html/rfc7230#section-3
        // All HTTP/ 1.1 messages consist of a start - line followed by a sequence
        // of octets in a format similar to the Internet Message Format
        // [RFC5322]: zero or more header fields(collectively referred to as
        // the "headers" or the "header section"), an empty line indicating the
        // end of the header section, and an optional message body.
        // HTTP - message = start - line
        //					* (header - field CRLF )
        //					CRLF
        //					[message - body]

        string startLine = await HttpMessageHelper.ReadStartLineAsync(responseStream, cancellationToken).ConfigureAwait(false);

        StatusLine          statusLine = StatusLine.Parse(startLine);
        HttpResponseMessage response   = new(statusLine.StatusCode);

        string headers = await HttpMessageHelper.ReadHeadersAsync(responseStream, cancellationToken).ConfigureAwait(false);

        HeaderSection headerSection = await HeaderSection.CreateNewAsync(headers).ConfigureAwait(false);

        HttpResponseContentHeaders headerStruct = headerSection.ToHttpResponseHeaders();

        HttpMessageHelper.AssertValidHeaders(headerStruct.ResponseHeaders, headerStruct.ContentHeaders);
        byte[]? contentBytes = await HttpMessageHelper.GetContentBytesAsync(responseStream, headerStruct, requestMethod, statusLine, cancellationToken).ConfigureAwait(false);

        contentBytes     = HttpMessageHelper.HandleGzipCompression(headerStruct.ContentHeaders, contentBytes);
        response.Content = contentBytes is null ? null : new ByteArrayContent(contentBytes);

        HttpMessageHelper.CopyHeaders(headerStruct.ResponseHeaders, response.Headers);
        if (response.Content is { })
 /// <summary>
 /// 设置请求方法
 /// </summary>
 /// <param name="httpMethod"></param>
 /// <returns></returns>
 public HttpClientExecutePart SetHttpMethod(HttpMethod httpMethod)
 {
     Method = httpMethod;
     return(this);
 }
Esempio n. 55
0
        private async Task <string> Request(string url, HttpMethod httpMethod)
        {
            var request = await Request(url, httpMethod, null, false);

            return(request);
        }
Esempio n. 56
0
        public static async Task <string> SendAndReceiveAsString(this HttpClient httpClient, HttpMethod httpMethod, string requestUri, object content = null)
        {
            var res = await httpClient.SendAndReceiveAsHttpMessage(httpMethod, requestUri, content);

            return(await res.Content.ReadAsStringAsync());
        }
Esempio n. 57
0
        /// <summary>
        /// Returns an object of type T created from the deserialization of the JSON response to the passed interface/method/version with the included parameters.
        /// </summary>
        /// <typeparam name="T">Type to deserialize into</typeparam>
        /// <param name="httpMethod">Determines GET or POST request</param>
        /// <param name="interfaceName">Name of web API interface to call</param>
        /// <param name="methodName">Name of web API method to call</param>
        /// <param name="methodVersion">Name of web API method version</param>
        /// <param name="parameters">List of parameters to append to the web API call</param>
        /// <returns>Deserialized object from JSON response</returns>
        private async Task <ISteamWebResponse <T> > SendWebRequestAsync <T>(HttpMethod httpMethod, string interfaceName, string methodName, int methodVersion, IList <SteamWebRequestParameter> parameters = null)
        {
            if (string.IsNullOrWhiteSpace(interfaceName))
            {
                throw new ArgumentNullException(nameof(interfaceName));
            }

            if (string.IsNullOrWhiteSpace(methodName))
            {
                throw new ArgumentNullException(nameof(methodName));
            }

            if (methodVersion <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(methodVersion));
            }

            if (parameters == null)
            {
                parameters = new List <SteamWebRequestParameter>();
            }

            parameters.Insert(0, new SteamWebRequestParameter("key", steamWebApiKey));

            HttpResponseMessage httpResponse = null;

            if (httpMethod == HttpMethod.GET)
            {
                string command = BuildRequestCommand(interfaceName, methodName, methodVersion, parameters);

                httpResponse = await httpClient.GetAsync(command).ConfigureAwait(false);

                httpResponse.EnsureSuccessStatusCode();
                if (httpResponse.Content == null)
                {
                    httpResponse = new HttpResponseMessage(HttpStatusCode.NoContent);
                }
            }
            else if (httpMethod == HttpMethod.POST)
            {
                // Null is passed instead of the parameters so that they are not appended to the URL.
                string command = BuildRequestCommand(interfaceName, methodName, methodVersion, null);

                // Instead, parameters are passed through this container.
                FormUrlEncodedContent content = BuildRequestContent(parameters);

                httpResponse = await httpClient.PostAsync(command, content).ConfigureAwait(false);

                httpResponse.EnsureSuccessStatusCode();
                if (httpResponse.Content == null)
                {
                    httpResponse = new HttpResponseMessage(HttpStatusCode.NoContent);
                }
            }

            var headers = httpResponse.Content?.Headers;

            // extract http headers that we care about
            SteamWebResponse <T> steamWebResponse = new SteamWebResponse <T>()
            {
                ContentLength      = headers?.ContentLength,
                ContentType        = headers?.ContentType?.MediaType,
                ContentTypeCharSet = headers?.ContentType?.CharSet,
                Expires            = headers?.Expires,
                LastModified       = headers?.LastModified,
            };

            // deserialize the content if we have any as indicated by the response code
            if (httpResponse.StatusCode != HttpStatusCode.NoContent && httpResponse.Content != null)
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync();

                responseContent       = CleanupResponseString(responseContent);
                steamWebResponse.Data = JsonConvert.DeserializeObject <T>(responseContent);
            }

            return(steamWebResponse);
        }
Esempio n. 58
0
        public static async Task <T> SendAndReceiveAs <T>(this HttpClient httpClient, HttpMethod httpMethod, string requestUri, object content = null)
        {
            var contentString = await httpClient.SendAndReceiveAsString(httpMethod, requestUri, content);

            return(JsonConvert.DeserializeObject <T>(contentString));
        }
Esempio n. 59
0
        private void GivenARequestWithAUrlAndMethod(DownstreamReRoute downstream, string url, HttpMethod method)
        {
            var context = new DownstreamContext(new DefaultHttpContext())
            {
                DownstreamReRoute = downstream,
                DownstreamRequest = new DownstreamRequest(new HttpRequestMessage()
                {
                    RequestUri = new Uri(url), Method = method
                }),
            };

            _context = context;
        }
Esempio n. 60
-1
        /// <summary>
        /// Sends a JSON OData request appending the SharePoint canary to the request header.
        /// Appending the canary to the request is necessary to perform write operations (e.g. create, update, delete list items)
        /// The canary is a security measure to prevent cross site scripting attacks
        /// </summary>
        /// <param name="uri">The request uri</param>
        /// <param name="method">The http method</param>
        /// <param name="requestContent">A stream containing the request content</param>
        /// <param name="clientHandler">The request client handler</param>
        /// <param name="authUtility">An instance of the auth helper to perform authenticated calls to SPO</param>
        /// <returns></returns>
        public static async Task<byte[]> SendODataJsonRequestWithCanary(Uri uri, HttpMethod method, Stream requestContent, HttpClientHandler clientHandler, SpoAuthUtility authUtility, bool _verbose)
        {
            verbose = _verbose;
            // Make a post request to {siteUri}/_api/contextinfo to get the canary
            var response = await HttpUtility.SendODataJsonRequest(
                new Uri(String.Format("{0}/_api/contextinfo", SpoAuthUtility.Current.SiteUrl)),
                HttpMethod.Post,
                null,
                clientHandler,
                SpoAuthUtility.Current);

            var serializer = new JavaScriptSerializer();
            var deserializedResponse = serializer.Deserialize<Dictionary<string, object>>(Encoding.UTF8.GetString(response, 0, response.Length));
            string canary = deserializedResponse["AuthURL"] as string;

            // Make the OData request passing the canary in the request headers
            return await HttpUtility.SendODataJsonRequest(
                uri,
                method,
                requestContent,
                clientHandler,
                SpoAuthUtility.Current, 
                new Dictionary<string, string> { 
                { "X-RequestDigest", canary  } 
                });
        }