/// <summary>
        /// Sends a json request.
        /// </summary>
        /// <typeparam name="T">The type of response we expect.</typeparam>
        /// <param name="verb">The http verb to use.</param>
        /// <param name="url">The url to send the request to.</param>
        /// <param name="payload">The object that will be serialized into json.</param>
        /// <param name="service">Optional parameter which uses headers for a specific service instead of defaults.</param>
        /// <returns>An IAsyncToken to listen to.</returns>
        /// <exception cref="NullReferenceException"></exception>
        protected IAsyncToken <HttpResponse <T> > SendJsonRequest <T>(
            HttpVerb verb,
            string url,
            object payload)
        {
            var token = new AsyncToken <HttpResponse <T> >();

            var request = new UnityWebRequest(
                url,
                verb.ToString().ToUpperInvariant())
            {
                downloadHandler = new DownloadHandlerBuffer(),
                disposeDownloadHandlerOnDispose = true,
                disposeUploadHandlerOnDispose   = true
            };

            var service = Services.Process(request);

            ApplyJsonPayload(payload, request);

            // Log after Processing
            Log(verb.ToString(), request.url, service, payload);

            _bootstrapper.BootstrapCoroutine(Wait(request, token));

            return(token);
        }
Beispiel #2
0
 /// <summary>
 /// 发送405响应(不接受请求类型)到客户端
 /// </summary>
 /// <param name="Response"></param>
 /// <param name="allow"></param>
 public static void Send405(this HttpResponseBase Response, HttpVerb allow)
 {
     Response.Clear();
     Response.StatusCode        = 405;
     Response.StatusDescription = "Method Not Allowed";
     Response.AppendHeader("Allow", allow.ToString());
     Response.Write(string.Format("Method Not Allowed, Except: {0}", allow.ToString()));
     Response.End();
 }
 /// <summary>
 /// 发送405响应(不接受请求类型)到客户端
 /// </summary>
 /// <param name="Response"></param>
 /// <param name="allow"></param>
 public static void Send405(this HttpResponseBase Response, HttpVerb allow)
 {
     Response.Clear();
     Response.StatusCode = 405;
     Response.StatusDescription = "Method Not Allowed";
     Response.AppendHeader("Allow", allow.ToString());
     Response.Write(string.Format("Method Not Allowed, Except: {0}", allow.ToString()));
     Response.End();
 }
Beispiel #4
0
        public void MakeReguestPut()
        {
            this.httpMethod       = HttpVerb.Put;
            this.strResponseValue = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);

            request.Method = httpMethod.ToString();
            HttpWebResponse response;

            try{
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException("Error code: " + response.StatusCode);
                }
                else
                {
                    Stream responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        StreamReader reader = new StreamReader(responseStream);
                        this.strResponseValue = reader.ReadToEnd();
                        reader.Close();
                    }
                }
            }
            catch (Exception e) {
                Console.WriteLine("No connection to server");
            }
        }
Beispiel #5
0
        /// <summary>
        /// Makes RESTful HTTP request
        /// </summary>
        /// <returns>Response of the request (could be JSON, XML or HTML etc. serialized into string)</returns>
        public async Task <string> MakeRequestAsync()
        {
            HttpWebRequest webRequest = null;

            // Create a HttpWebRequest instance for web request
            try
            {
                webRequest             = (HttpWebRequest)WebRequest.Create(_endPoint);
                webRequest.Method      = _httpMethod.ToString();
                webRequest.ContentType = _contentType;
                if (_headers?.Count > 0)
                {
                    foreach (KeyValuePair <string, string> header in _headers)
                    {
                        webRequest.Headers[header.Key] = header.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to create HttpWebRequest handler. " + ex.Message);
            }

            if (webRequest != null)
            {
                return(await ProcessWebRequestAsync(webRequest));
            }

            return(null);
        }
        /// <summary>
        /// Sends a file!
        /// </summary>
        /// <typeparam name="T">The type of response we expect.</typeparam>
        /// <param name="verb">The http verb to use.</param>
        /// <param name="url">The url to send the request to.</param>
        /// <param name="fields">Optional fields that will _precede_ the file.</param>
        /// <param name="file">The file, which will be named "file".</param>
        /// <returns></returns>
        private IAsyncToken <HttpResponse <T> > SendFile <T>(
            HttpVerb verb,
            string url,
            IEnumerable <Tuple <string, string> > fields,
            ref byte[] file)
        {
            var token = new AsyncToken <HttpResponse <T> >();

            var form = new WWWForm();

            foreach (var tuple in fields)
            {
                form.AddField(tuple.Item1, tuple.Item2);
            }

            form.AddBinaryData("file", file);

            var request = UnityWebRequest.Post(
                url,
                form);

            request.method          = verb.ToString().ToUpperInvariant();
            request.useHttpContinue = false;
            request.downloadHandler = new DownloadHandlerBuffer();
            request.disposeDownloadHandlerOnDispose = true;
            request.disposeUploadHandlerOnDispose   = true;

            ApplyHeaders(Headers, request);

            _bootstrapper.BootstrapCoroutine(Wait(request, token));

            return(token);
        }
        /// <summary>
        /// Set the HTTP verb (or method)
        /// </summary>
        public RequestFluent Verb(HttpVerb verb)
        {
            // set the verb
            this._verb = verb.ToString();

            return(this);
        }
Beispiel #8
0
        public string makeRequest(HttpVerb httpMethod)
        {
            string strResponseValue = string.Empty;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(endpoint);

            request.Method = httpMethod.ToString();



            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException($"Error Code: {response.StatusCode}");
                }

                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            strResponseValue = reader.ReadToEnd();
                        }
                    }
                }
            }

            return(strResponseValue);
        }
        /// <summary>
        /// Sends a JSON request.
        /// </summary>
        /// <typeparam name="T">Type of response.</typeparam>
        /// <param name="verb">HTTP verb.</param>
        /// <param name="url">Complete endpoint url.</param>
        /// <param name="payload">Object to send.</param>
        /// <returns></returns>
        private IAsyncToken <HttpResponse <T> > SendRequest <T>(
            HttpVerb verb,
            string url,
            object payload)
        {
            Log.Info(this,
                     "{0} {1}",
                     verb.ToString().ToUpperInvariant(),
                     url);

            var token = new AsyncToken <HttpResponse <T> >();

            byte[] bytes = null;
            if (null != payload)
            {
                _serializer.Serialize(payload, out bytes);
            }

            var request = new WWW(
                url,
                bytes,
                HeaderDictionary());

            _bootstrapper.BootstrapCoroutine(Wait(request, token));

            return(token);
        }
Beispiel #10
0
        public string MakeRequest()
        {
            string         stringResponseValue = string.Empty;
            HttpWebRequest request             = (HttpWebRequest)WebRequest.Create(EndPoint);

            HttpMethod     = HttpVerb.GET;
            request.Method = HttpMethod.ToString();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException($"Error code: {response.StatusCode}");
                }
                //Precess the response stream
                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            stringResponseValue = reader.ReadToEnd();
                        } //End of StreamReader
                    }
                }         //End of using ResponseStream
            }             //End of using Response
            return(stringResponseValue);
        }
        private void MockResponse(HttpVerb verb, HttpStatusCode status, string response)
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage(status);

            responseMessage.Content = new StringContent(response);

            switch (verb)
            {
            case HttpVerb.DELETE:
                _mockHttpClient.Setup(x => x.DeleteAsync(It.IsAny <string>()))
                .ReturnsAsync(responseMessage);
                break;

            case HttpVerb.GET:
                _mockHttpClient.Setup(x => x.GetAsync(It.IsAny <string>()))
                .ReturnsAsync(responseMessage);
                break;

            case HttpVerb.POST:
                _mockHttpClient.Setup(x => x.PostAsync(It.IsAny <string>(), It.IsAny <HttpContent>()))
                .ReturnsAsync(responseMessage);
                break;

            case HttpVerb.PUT:
                _mockHttpClient.Setup(x => x.PutAsync(It.IsAny <string>(), It.IsAny <HttpContent>()))
                .ReturnsAsync(responseMessage);
                break;

            default:
                throw new NotImplementedException($"HTTP Verb '{verb.ToString()}' not implemented");
            }
        }
Beispiel #12
0
        /// <summary>
        /// HTTP Web Request
        /// </summary>
        /// <param name="url"></param>
        /// <param name="webMethod">webMethod</param>
        /// <param name="cookies"></param>
        /// <param name="postDataValue"></param>
        /// <returns></returns>
        private static HttpWebResult PrepareInkWebRequest(HP.DeviceAutomation.IDevice device, Uri url, HttpVerb webMethod, string cookies, string postDataValue)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Accept = "*/*";
            if (device is SiriusUIv3Device)
            {
                webRequest.Headers.Add("Accept-Language", "en-US");
                webRequest.ContentType = "text/xml";
            }
            else
            {
                webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.5");
                webRequest.ContentType = "text/xml; charset=UTF-8";
            }
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            if (!string.IsNullOrEmpty(cookies))
            {
                webRequest.Headers.Add("Cookie", cookies);
            }

            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.Method = webMethod.ToString();
            if (webMethod == HttpVerb.GET)
            {
                return(HttpWebEngine.Get(webRequest));
            }
            if (webMethod == HttpVerb.PUT)
            {
                return(HttpWebEngine.Put(webRequest, postDataValue));
            }
            return(null);
        }
        internal static void AddAuthenticationHeaders(HttpPipelineRequest request, Uri uri, HttpVerb method, ReadOnlyMemory <byte> content, byte[] secret, string credential)
        {
            string contentHash = null;

            using (var alg = SHA256.Create())
            {
                // TODO (pri 3): ToArray should nopt be called here. Instead, TryGetArray, or PipelineContent should do hashing on the fly
                contentHash = Convert.ToBase64String(alg.ComputeHash(content.ToArray()));
            }

            using (var hmac = new HMACSHA256(secret))
            {
                var host         = uri.Host;
                var pathAndQuery = uri.PathAndQuery;

                string         verb          = method.ToString().ToUpper();
                DateTimeOffset utcNow        = DateTimeOffset.UtcNow;
                var            utcNowString  = utcNow.ToString("r");
                var            stringToSign  = $"{verb}\n{pathAndQuery}\n{utcNowString};{host};{contentHash}";
                var            signature     = Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(stringToSign))); // Calculate the signature
                string         signedHeaders = "date;host;x-ms-content-sha256";                                                 // Semicolon separated header names

                // TODO (pri 3): should date header writing be moved out from here?
                request.AddHeader("Date", utcNowString);
                request.AddHeader("x-ms-content-sha256", contentHash);
                request.AddHeader("Authorization", $"HMAC-SHA256 Credential={credential}, SignedHeaders={signedHeaders}, Signature={signature}");
            }
        }
        /// <summary>
        /// Sends a JSON request.
        /// </summary>
        /// <typeparam name="T">Type of response.</typeparam>
        /// <param name="verb">HTTP verb.</param>
        /// <param name="url">Complete endpoint url.</param>
        /// <param name="payload">Object to send.</param>
        /// <returns></returns>
        private IAsyncToken <HttpResponse <T> > SendRequest <T>(
            HttpVerb verb,
            string url,
            object payload)
        {
            var data        = Services.ResolveServiceData(url);
            var service     = data.Item1;
            var resolvedUrl = data.Item2;
            var headers     = data.Item3;

            Log(verb.ToString(), resolvedUrl, service, payload);

            var token = new AsyncToken <HttpResponse <T> >();

            byte[] bytes = null;
            if (null != payload)
            {
                _serializer.Serialize(payload, out bytes);
            }

            var request = new WWW(
                resolvedUrl,
                bytes,
                HeaderDictionary(headers));

            _bootstrapper.BootstrapCoroutine(Wait(request, token));

            return(token);
        }
Beispiel #15
0
        private string MakeRequestStream(Uri url, HttpVerb httpVerb, byte[] arr)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = httpVerb.ToString();

            if (httpVerb == HttpVerb.POST)
            {
                request.ContentType   = "octect/stream";
                request.ContentLength = arr.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(arr, 0, arr.Length);
                //requestStream.Close();
            }

            try
            {
                using (HttpWebResponse response
                           = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader
                        = new StreamReader(response.GetResponseStream());

                    return(reader.ReadToEnd());
                }
            }
            catch
            {
                throw;
            }
        }
Beispiel #16
0
        /// <summary>
        /// Makes a restful call using supplied information.
        /// </summary>
        /// <typeparam name="TResult">Return type to convert response to (if you provide VoidResultType then null will be returned - basically a void call).</typeparam>
        /// <param name="uri">Uri to make the request against.</param>
        /// <param name="httpVerb">HTTP verb to use.</param>
        /// <param name="body">Optional body object to send (use null if not needed).</param>
        /// <param name="cookieJar">Optional cookie to use (use null if not needed).</param>
        /// <param name="headerJar">Optional headers to use (use null if not needed).</param>
        /// <param name="saveResponseHeadersAction">Optional action to use to save response headers (use null if not needed).</param>
        /// <param name="contentType">Content type to use for request.</param>
        /// <param name="acceptType">Content type to use for response.</param>
        /// <param name="timeout">Timeout to use.</param>
        /// <param name="serializer">Serializer to use.</param>
        /// <returns>Converted response to the specified type.</returns>
        public static TResult Call <TResult>(
            Uri uri,
            HttpVerb httpVerb,
            object body,
            CookieJar cookieJar,
            HeaderJar headerJar,
            Action <KeyValuePair <string, string>[]> saveResponseHeadersAction,
            ContentType contentType,
            ContentType acceptType,
            TimeSpan timeout,
            IStringSerializeAndDeserialize serializer)
            where TResult : class
        {
            var httpVerbAsString = httpVerb.ToString().ToUpperInvariant();

            return(Call <TResult>(
                       uri,
                       httpVerbAsString,
                       body,
                       cookieJar,
                       headerJar,
                       saveResponseHeadersAction,
                       contentType,
                       acceptType,
                       timeout,
                       serializer));
        }
Beispiel #17
0
 /// <summary>
 /// 发送请求方法
 /// </summary>
 protected void MakeRequest()
 {
     if (string.IsNullOrWhiteSpace(url))
     {
         throw new ArgumentNullException("url is empty");
     }
     try
     {
         HttpWebRequest request = this.GetWebRequest(url);
         request.CookieContainer   = Cookies.Container;
         request.Method            = method.ToString().ToUpper();
         request.AllowAutoRedirect = false;
         if (method == HttpVerb.Get || method == HttpVerb.Head)
         {
             ExecuteRequestWithoutBody(request);
         }
         else
         {
             request.ContentType = body.GetContentType();
             ExecuteRequestWithBody(request);
         }
     }
     catch (WebException webEx)
     {
         action.Fail(webEx);
     }
 }
Beispiel #18
0
        /// <summary>
        /// Create a webrequest according to Endpoint
        /// </summary>
        /// <param name="EndPoint">It is url of object location</param>
        /// <returns>Return a web request</returns>
        protected WebRequest RequestBase(string EndPoint)
        {
            WebRequest request = WebRequest.Create(EndPoint);

            request.Method = httpMethod.ToString();

            return(request);
        }
Beispiel #19
0
        /// <summary>
        /// Send Request with given class to serialized data into json format.
        /// </summary>
        /// <param name="EndPoint">URL To the web server</param>
        /// <param name="httpMethod">HTTP Method of web request</param>
        /// <param name="serializedClass">class of data for json serialization</param>
        /// <returns></returns>
        public ResponseMessage Request(string EndPoint, HttpVerb httpMethod, string serializedClass)
        {
            WebRequest request = RequestBase(EndPoint, httpMethod.ToString());

            this.httpMethod = httpMethod;
            string response = SendRequest(request, serializedClass).Result;

            return(JsonConvert.DeserializeObject <ResponseMessage>(response));
        }
        public static HttpWebRequest CreateJsonHttpWebRequest(Uri uri, HttpVerb verb, string username, string password)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);

            JSONSerializer.SetBasicAuthHeader(request, username, password);
            request.Method      = verb.ToString();
            request.ContentType = "application/json; charset=utf-8";

            return(request);
        }
Beispiel #21
0
        /// <summary>
        /// 根据Url获取http响应
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="method">Http方法</param>
        /// <returns>Http响应消息</returns>
        public static HttpWebResponse GetUrlResponse(string url, HttpVerb method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method      = method.ToString();
            req.ContentType = "application/json;charset=UTF-8";//text/plain; charset=utf-8
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            return(res);
        }
Beispiel #22
0
        /// <summary>
        /// Configurations the HTTP request message.
        /// </summary>
        /// <param name="httpRequestMessage">The HTTP request message.</param>
        /// <param name="serviceUri">The service URI.</param>
        /// <param name="httpVerb">The HTTP verb.</param>
        /// <param name="httpContentType">Type of the HTTP content.</param>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        public static HttpRequestMessage ConfigHttpRequestMessage(this HttpRequestMessage httpRequestMessage, Uri serviceUri, HttpVerb httpVerb, string httpContentType, StringContent content)
        {
            content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(httpContentType);
            httpRequestMessage.Content  = content;
            httpRequestMessage.Method   = new HttpMethod(httpVerb.ToString());
            httpRequestMessage.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse(httpContentType));
            httpRequestMessage.RequestUri = serviceUri;

            return(httpRequestMessage);
        }
Beispiel #23
0
        private HttpWebRequest CreateRequest(HttpVerb verb)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(apiUri);

            req.Method      = verb.ToString();
            req.ContentType = "text/json";
            SetRequestHeaders(req);

            return(req);
        }
Beispiel #24
0
        private string MakeResponse(string sessionToken, HttpVerb method, string parameters, string postData)
        {
            string _apiUrlBase  = Settings.ApiUrlBase;
            var    requestedUrl = _apiUrlBase + parameters;
            var    webRequest   = (HttpWebRequest)WebRequest.Create(requestedUrl);

            webRequest.Method      = method.ToString();
            webRequest.ContentType = "application/json";
            // webRequest.ContentLength = 0;
            webRequest.Accept = "application/json; charset=utf-8";
            if (!string.IsNullOrEmpty(sessionToken))
            {
                webRequest.Headers.Add("X-SessionToken", sessionToken);
            }

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            Stream dataStream = webRequest.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (Exception ex)
            {
                return(null);
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new ApplicationException($"Request failed. Received HTTP {response.StatusCode}");
            }

            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        var respone = reader.ReadToEnd();

                        Console.Write(respone);

                        return(respone);
                    }
                }
            }

            return("");
        }
Beispiel #25
0
        /// <summary>
        /// Sends an HTTP request to the server and handles the response.
        /// </summary>
        /// <param name="verb">The HTTP verb to use for the request.</param>
        /// <param name="urlParameter">Any URL parameters to send.</param>
        /// <param name="bodyParameter">Any body parameters to send.</param>
        /// <returns>The HTTP Response information.</returns>
        /// <exception cref="System.NotImplementedException">Thrown when the HTTP verb given has not been
        /// implemented yet.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when the request was already sent by
        /// the client instance or the URI is invalid.</exception>
        public async Task <HttpResponse> Send(HttpVerb verb, IHttpRequestParameter urlParameter = null, IHttpRequestParameter bodyParameter = null)
        {
            string              fullRequestUrl  = $"{_requestUrl}{ConstructParameterString(urlParameter)}";
            HttpContent         content         = new StringContent(ConstructParameterString(bodyParameter));
            HttpResponseMessage responseMessage = null;

            try
            {
                switch (verb)
                {
                case HttpVerb.DELETE:
                    responseMessage = await _httpClient.DeleteAsync(fullRequestUrl);

                    break;

                case HttpVerb.GET:
                    responseMessage = await _httpClient.GetAsync(fullRequestUrl);

                    break;

                case HttpVerb.POST:
                    responseMessage = await _httpClient.PostAsync(fullRequestUrl, content);

                    break;

                case HttpVerb.PUT:
                    responseMessage = await _httpClient.PutAsync(fullRequestUrl, content);

                    break;

                default:
                    throw new NotImplementedException($"HTTP Verb not implemented: {verb.ToString()}");
                }
            }
            catch (HttpRequestException ex)
            {
                string error = ExceptionUtilities.GetAllExceptionMessages(ex);
                return(new HttpResponse(
                           fullRequestUrl,
                           System.Net.HttpStatusCode.InternalServerError,
                           error,
                           verb
                           ));
            }

            string responseBody = await responseMessage.Content.ReadAsStringAsync();

            return(new HttpResponse(
                       fullRequestUrl,
                       responseMessage.StatusCode,
                       responseBody,
                       verb
                       ));
        }
Beispiel #26
0
        /// <summary>
        ///     记录确认状态时候的信息
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="url"></param>
        /// <param name="httpVerb"></param>
        /// <returns></returns>
        public static ExceptionData LogEnsureSuccessed(Exception exception, string url, HttpVerb httpVerb)
        {
            var ed = new ExceptionData {
                Exception = exception, Message = "确认Http状态码时异常"
            };

            ed.Data.Add("url", url);
            ed.Data.Add("httpverb", httpVerb.ToString());
            ed.Data.Add("type", "ensuresuccessed");
            return(ed);
        }
            public static void RegisterRoute(string route, HttpVerb verb)
            {
                if (routes.ContainsKey(route))
                {
                    return;
                }

                Console.WriteLine("Added route " + route + " for verb " + verb.ToString());

                routes.Add(route, verb);
            }
Beispiel #28
0
        /// <summary>
        ///     记录确认状态时候的信息
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="url"></param>
        /// <param name="httpVerb"></param>
        /// <returns></returns>
        public static ExceptionData LogRequestTimeout(Exception exception, string url, HttpVerb httpVerb)
        {
            var ed = new ExceptionData {
                Exception = exception, Message = "请求时候的超时异常"
            };

            ed.Data.Add("url", url);
            ed.Data.Add("httpverb", httpVerb.ToString());
            ed.Data.Add("type", "request");
            ed.Data.Add("errorType", "timeout");
            return(ed);
        }
Beispiel #29
0
        public HttpWebRequest CreateRequest(HttpVerb verb, string action, bool needsAuthentication = true)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Host + action);

            request.Method = verb.ToString().ToUpper();
            if (needsAuthentication)
            {
                request.Headers[HttpRequestHeader.Authorization] = "Bearer " + AccessToken;
            }

            return(request);
        }
Beispiel #30
0
        private static void MakeRequest(string contentType, HttpVerb method, string url, object parameters, Action <WebHeaderCollection, Stream> successCallback, Action <WebException> failCallback)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters object cannot be null");
            }

            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException("url is empty");
            }

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                request.CookieContainer = cookies;
                request.Method          = method.ToString();

                switch (method)
                {
                case HttpVerb.Delete:
                case HttpVerb.Post:
                case HttpVerb.Put:
                case HttpVerb.Patch:
                    request.ContentType = contentType;
                    request.BeginGetRequestStream(callbackResult =>
                    {
                        var tmprequest = (HttpWebRequest)callbackResult.AsyncState;
                        var postStream = tmprequest.EndGetRequestStream(callbackResult);
                        var postbody   = Utils.SerializeQueryString(parameters);
                        var byteArray  = System.Text.Encoding.UTF8.GetBytes(postbody);
                        postStream.Write(byteArray, 0, byteArray.Length);
                        postStream.Flush();
                        postStream.Dispose();
                        tmprequest.BeginGetResponse(ProcessCallback(successCallback, failCallback), tmprequest);
                    }, request);
                    break;

                case HttpVerb.Get:
                case HttpVerb.Head:
                    request.BeginGetResponse(ProcessCallback(successCallback, failCallback), request);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(method), method, null);
                }
            }
            catch (WebException webEx)
            {
                failCallback(webEx);
            }
        }
Beispiel #31
0
        private void AddMethod(Effect effect, HttpVerb verb, string resource, ICollection <Condition> conditions = null)
        {
            if (verb == null)
            {
                throw new ArgumentNullException(nameof(verb));
            }

            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            if (!_pathRegex.IsMatch(resource))
            {
                throw new Exception($"Invalid resource path: {resource}. Path should match {_pathRegex}");
            }

            var cleanedResource = resource.First() == '/' ? resource.Substring(1) : resource;

            ApiGatewayArn arn = new ApiGatewayArn
            {
                RestApiId    = _restApiId,
                Region       = _region,
                Stage        = _stage,
                AwsAccountId = AwsAccountId,
                Verb         = verb.ToString(),
                Resource     = cleanedResource
            };

            switch (effect)
            {
            case Effect.Deny:
                _denyMethods.Add(new Method
                {
                    ArnResource = arn.ToString(),
                    Conditions  = ConditionsToDictionary(conditions)
                });
                return;

            case Effect.Allow:
                _allowMethods.Add(new Method
                {
                    ArnResource = arn.ToString(),
                    Conditions  = ConditionsToDictionary(conditions)
                });
                return;
            }
        }
        /// <summary>
        /// Sets up the HttpContext objects to simulate a request.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="httpVerb"></param>
        /// <param name="formVariables"></param>
        /// <param name="headers"></param>
        protected virtual HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection formVariables, NameValueCollection headers)
        {
            HttpContext.Current = null;

            ParseRequestUrl(url);

            if (this.responseWriter == null)
            {
                this.builder = new StringBuilder();
                this.responseWriter = new StringWriter(builder);
            }

            SetHttpRuntimeInternals();

            string query = ExtractQueryStringPart(url);

            if (formVariables != null)
                _formVars.Add(formVariables);

            if (_formVars.Count > 0)
                httpVerb = HttpVerb.POST; //Need to enforce this.

            if (headers != null)
                _headers.Add(headers);

            this.workerRequest = new SimulatedHttpRequest(ApplicationPath, PhysicalApplicationPath, PhysicalPath, Page, query, this.responseWriter, host, port, httpVerb.ToString());

            this.workerRequest.Form.Add(_formVars);
            this.workerRequest.Headers.Add(_headers);

            if (_referer != null)
                this.workerRequest.SetReferer(_referer);

            InitializeSession();

            InitializeApplication();

            #region Console Debug INfo

            Console.WriteLine("host: " + host);
            Console.WriteLine("virtualDir: " + applicationPath);
            Console.WriteLine("page: " + localPath);
            Console.WriteLine("pathPartAfterApplicationPart: " + _page);
            Console.WriteLine("appPhysicalDir: " + physicalApplicationPath);
            Console.WriteLine("Request.Url.LocalPath: " + HttpContext.Current.Request.Url.LocalPath);
            Console.WriteLine("Request.Url.Host: " + HttpContext.Current.Request.Url.Host);
            Console.WriteLine("Request.FilePath: " + HttpContext.Current.Request.FilePath);
            Console.WriteLine("Request.Path: " + HttpContext.Current.Request.Path);
            Console.WriteLine("Request.RawUrl: " + HttpContext.Current.Request.RawUrl);
            Console.WriteLine("Request.Url: " + HttpContext.Current.Request.Url);
            Console.WriteLine("Request.Url.Port: " + HttpContext.Current.Request.Url.Port);
            Console.WriteLine("Request.ApplicationPath: " + HttpContext.Current.Request.ApplicationPath);
            Console.WriteLine("Request.PhysicalPath: " + HttpContext.Current.Request.PhysicalPath);
            Console.WriteLine("HttpRuntime.AppDomainAppPath: " + HttpRuntime.AppDomainAppPath);
            Console.WriteLine("HttpRuntime.AppDomainAppVirtualPath: " + HttpRuntime.AppDomainAppVirtualPath);
            Console.WriteLine("HostingEnvironment.ApplicationPhysicalPath: " + HostingEnvironment.ApplicationPhysicalPath);
            Console.WriteLine("HostingEnvironment.ApplicationVirtualPath: " + HostingEnvironment.ApplicationVirtualPath);

            #endregion

            return this;
        }
Beispiel #33
0
        private static string GenerateSignature(bool multipart, Dictionary<string, object> parameters, Uri requestUri, AccessTokens tokens, HttpVerb verb )
        {
            IEnumerable<KeyValuePair<string, object>> nonSecretParameters = null;

            if (multipart)
            {
                nonSecretParameters = (from p in parameters
                                       where (!Common.SecretParameters.Contains(p.Key) && p.Key.StartsWith("oauth_"))
                                       select p);
            }
            else
            {
                nonSecretParameters = (from p in parameters
                                       where (!Common.SecretParameters.Contains(p.Key))
                                       select p);
            }

            Uri urlForSigning = requestUri;

            // Create the base string. This is the string that will be hashed for the signature.
            string signatureBaseString = string.Format(
                CultureInfo.InvariantCulture,
                "{0}&{1}&{2}",
                verb.ToString().ToUpper(CultureInfo.InvariantCulture),
                UrlUtility.UrlEncode(UrlUtility.NormalizeUrl(urlForSigning)),
                UrlUtility.UrlEncode(nonSecretParameters));

            // Create our hash key (you might say this is a password)
            string key = string.Format(
                CultureInfo.InvariantCulture,
                "{0}&{1}",
                UrlUtility.UrlEncode(tokens.ConsumerSecret),
                UrlUtility.UrlEncode(tokens.AccessTokenSecret));

            // Generate the hash
            HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
            byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));
            return Convert.ToBase64String(signatureBytes);
        }