예제 #1
0
 public RestRequest(HttpVerb verb, string command, IDictionary<string, string> headers, IDictionary<string, object> parameters)
 {
     this.Verb = verb;
     this.Command = command;
     this.Headers = headers;
     this.Parameters = parameters;
 }
예제 #2
0
        public ApiRequestObject(ApiRequest request)
        {
            Verb = request.Verb;
            ActionName = request.ActionName;
            Arguments = request.ActionArguments;
            Headers = request.Headers;
            Data = request.Data;

            Respond = delegate(object data, Dictionary<string, object> options) {
                options = Script.Or(options, new Dictionary<string, object>());

                HttpStatusCode statusCode = Script.Or((HttpStatusCode)options["statusCode"],
                                                      (data == null) ? HttpStatusCode.NoContent : HttpStatusCode.OK);

                ServerResponse response = new ServerResponse(statusCode);

                if (data != null) {
                    if (data is string) {
                        response.AddTextContent((string)data, Script.Or((string)options["contentType"], "text/plain"));
                    }
                    else {
                        response.AddObjectContent(data);
                    }
                }

                return Deferred.Create<ServerResponse>(response).Task;
            };
        }
예제 #3
0
        public static void SetupOAuth(bool multipart, HttpVerb verb, bool useOAuth, Dictionary<string, object> parameters, AccessTokens tokens, Uri requestUri)
        {
            // We only sign oauth requests
            if (!useOAuth)
            {
                return;
            }

            // Add the OAuth parameters
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_nonce", Core.Common.Utility.GenerateNonce());
            parameters.Add("oauth_timestamp", Core.Common.Utility.GenerateTimeStamp());
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_consumer_key", tokens.ConsumerKey);
            parameters.Add("oauth_consumer_secret", tokens.ConsumerSecret);

            if (!string.IsNullOrEmpty(tokens.AccessToken))
            {
                parameters.Add("oauth_token", tokens.AccessToken);
            }

            if (!string.IsNullOrEmpty(tokens.AccessTokenSecret))
            {
                parameters.Add("oauth_token_secret", tokens.AccessTokenSecret);
            }

            string signature = GenerateSignature(multipart, parameters, requestUri, tokens, verb);

            // Add the signature to the oauth parameters
            parameters.Add("oauth_signature", signature);
        }
        public static bool ShouldValidate(
            this IAbpAntiForgeryManager manager,
            IAbpAntiForgeryWebConfiguration antiForgeryWebConfiguration,
            MethodInfo methodInfo, 
            HttpVerb httpVerb, 
            bool defaultValue)
        {
            if (!antiForgeryWebConfiguration.IsEnabled)
            {
                return false;
            }

            if (methodInfo.IsDefined(typeof(ValidateAbpAntiForgeryTokenAttribute), true))
            {
                return true;
            }

            if (ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<DisableAbpAntiForgeryTokenValidationAttribute>(methodInfo) != null)
            {
                return false;
            }

            if (antiForgeryWebConfiguration.IgnoredHttpVerbs.Contains(httpVerb))
            {
                return false;
            }

            if (methodInfo.DeclaringType?.IsDefined(typeof(ValidateAbpAntiForgeryTokenAttribute), true) ?? false)
            {
                return true;
            }

            return defaultValue;
        }
예제 #5
0
        public async Task<dynamic> Request(HttpVerb method, string path, string content)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = Servers.First(x => x.RetryAfter == null || x.RetryAfter < DateTimeOffset.Now).Address;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    HttpResponseMessage response;

                    switch (method)
                    {
                        case HttpVerb.POST:
                            response = await client.PostAsJsonAsync(sqlPath, new { stmt = content.TrimEnd(new[] { ' ', ';' }) });
                            break;
                        case HttpVerb.GET:
                        default:
                            response = await client.GetAsync(path);
                            break;
                    }
                    
                    response.EnsureSuccessStatusCode();

                    return JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
                }
                catch (HttpRequestException e)
                {
                    Debug.Write(e.ToString());
                    return null;
                }
            }
        }
        public static ProviderServiceInteraction GetMatchingInteraction(this NancyContext context, HttpVerb method, string path)
        {
            if (!context.Items.ContainsKey(PactMockInteractionsKey))
            {
                throw new InvalidOperationException("No mock interactions have been registered");
            }

            var interactions = (IEnumerable<ProviderServiceInteraction>)context.Items[PactMockInteractionsKey];

            if (interactions == null)
            {
                throw new ArgumentException("No matching mock interaction has been registered for the current request");
            }

            var matchingInteractions = interactions.Where(x =>
                x.Request.Method == method &&
                x.Request.Path == path).ToList();

            if (matchingInteractions == null || !matchingInteractions.Any())
            {
                throw new ArgumentException("No matching mock interaction has been registered for the current request");
            }

            if (matchingInteractions.Count() > 1)
            {
                throw new ArgumentException("More than one matching mock interaction has been registered for the current request");
            }

            return matchingInteractions.Single();
        }
예제 #7
0
 /// <summary>
 /// Createa a new <see cref="DynamicApiActionInfo"/> object.
 /// </summary>
 /// <param name="actionName">Name of the action in the controller</param>
 /// <param name="verb">The HTTP verb that is used to call this action</param>
 /// <param name="method">The method which will be invoked when this action is called</param>
 public DynamicApiActionInfo(string actionName, HttpVerb verb, MethodInfo method, IFilter[] filters = null)
 {
     ActionName = actionName;
     Verb = verb;
     Method = method;
     Filters = filters ?? new IFilter[] { }; //Assigning or initialzing the action filters.
 }
 public EntitySetEndPointAnnotation(
     string name,
     HttpVerb[] allowedVerbs)
     : base()
 {
     this.Name = name;
     this.AllowedVerbs = new Collection<HttpVerb>(allowedVerbs);
 }
예제 #9
0
        /// <summary>
        /// Checks whether the handler can handle the incoming request.
        /// </summary>
        public bool CanHandle(HttpContext context, HttpVerb verb, string url)
        {
            if (url == "/last-update")
                return true;

            FileInfo file;
            return TryGet(url, out file);
        }
        public HttpClient CreateFor(HttpVerb verb)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return client;
        }
예제 #11
0
 public void Compare(HttpVerb expected, HttpVerb actual)
 {
     _reporter.ReportInfo(String.Format("{0} has method set to {1}", _messagePrefix, expected));
     if (!expected.Equals(actual))
     {
         _reporter.ReportError(expected: expected, actual: actual);
         return;
     }
 }
 public void Compare(HttpVerb method1, HttpVerb method2)
 {
     _reporter.ReportInfo(String.Format("{0} has method set to {1}", _messagePrefix, method1));
     if (!method1.Equals(method2))
     {
         _reporter.ReportError(expected: method1, actual: method2);
         return;
     }
 }
예제 #13
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();
 }
예제 #14
0
        public HttpMethod Convert(HttpVerb from)
        {
            if (!Map.ContainsKey(from))
            {
                throw new ArgumentException(String.Format("Cannot map HttpVerb.{0} to a HttpMethod, no matching item has been registered.", from));
            }

            return Map[from];
        }
예제 #15
0
        public ApiRequest(Controller controller, HttpVerb verb, string actionName, Dictionary<string, string> headers, Dictionary<string, string> args)
        {
            _controller = controller;

            _verb = verb;
            _actionName = actionName;
            _headers = headers;

            _actionArgs = args;
        }
예제 #16
0
        public ComparisonResult Compare(HttpVerb expected, HttpVerb actual)
        {
            var result = new ComparisonResult("has method {0}", expected);

            if (!expected.Equals(actual))
            {
                result.RecordFailure(new DiffComparisonFailure(expected, actual));
                return result;
            }

            return result;
        }
예제 #17
0
        public RestRequest(HttpVerb verb, string command, object headers, object parameters)
        {
            this.Verb = verb;
            this.Command = command;

            this.Headers = RestRequest._headersDictionaryTypeInfo.IsAssignableFrom(headers.GetType().GetTypeInfo()) ?
                (IDictionary<string, string>)headers :
                RestRequest._objectConvertor.ToStringDictionary(headers);

            this.Parameters = RestRequest._parametersDictionaryTypeInfo.IsAssignableFrom(parameters.GetType().GetTypeInfo()) ?
                (IDictionary<string, object>)parameters :
                RestRequest._objectConvertor.ToObjectDictionary(parameters);
        }
예제 #18
0
        /// <summary>
        /// Generates the authorization header.
        /// </summary>
        /// <returns>The string value of the HTTP header to be included for OAuth requests.</returns>
        public static string GenerateAuthorizationHeader(string realm, bool multipart, Dictionary<string, object> parameters, Uri requestUri, AccessTokens tokens, HttpVerb verb)
        {
            StringBuilder authHeaderBuilder = new StringBuilder();
            authHeaderBuilder.AppendFormat("OAuth realm=\"{0}\"", realm);

            var sortedParameters = from p in parameters
                                   where Common.OAuthParametersToIncludeInHeader.Contains(p.Key)
                                   orderby p.Key, UrlUtility.UrlEncode((p.Value.GetType() == typeof(string)) ? p.Value as string : "")
                                   select p;

            foreach (var item in sortedParameters)
            {
                authHeaderBuilder.AppendFormat(
                    ",{0}=\"{1}\"",
                    UrlUtility.UrlEncode(item.Key),
                    UrlUtility.UrlEncode(item.Value as string));
            }

            authHeaderBuilder.AppendFormat(",oauth_signature=\"{0}\"", UrlUtility.UrlEncode(parameters["oauth_signature"] as string));

            return authHeaderBuilder.ToString();
        }
예제 #19
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);
        }
예제 #20
0
 public RequestBuilder(string url, HttpVerb method)
 {
     this.url    = url;
     this.method = method;
 }
예제 #21
0
        /// <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 (ResponseWriter == null)
            {
                _builder       = new StringBuilder();
                ResponseWriter = new StringWriter(_builder);
            }

            SetHttpRuntimeInternals();

            var 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);
            }

            WorkerRequest = new SimulatedHttpRequest(ApplicationPath, PhysicalApplicationPath, PhysicalPath, Page, query, ResponseWriter, Host, Port, httpVerb.ToString());

            WorkerRequest.Form.Add(_formVars);
            WorkerRequest.Headers.Add(_headers);

            if (_referer != null)
            {
                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);
            //if (HttpContext.Current != null)
            //{
            //    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);
        }
예제 #22
0
        //
        //  Request Logic
        #region SmartsheetHttpClient Request Logic
        public async Task <TResult> ExecuteRequest <TResult, T>(HttpVerb verb, string url, T data, IList <Tuple <string, string> > headers = null, bool deserializeAsJson = true)
        {
            //this.ValidateRequestInjectedResult(typeof(TResult));

            //this.ValidateRequestInjectedType(typeof(T));

            this.ValidateClientParameters();

            this.InitiazeNewRequest();

            while (_RetryRequest && (_RetryCount < _AttemptLimit))
            {
                try
                {
                    if (_WaitTime > 0)
                    {
                        Thread.Sleep(_WaitTime);
                    }

                    HttpResponseMessage response;

                    var serializerSettings = new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ContractResolver  = new CamelCasePropertyNamesContractResolver()
                    };

                    var serializedData = JsonConvert.SerializeObject(data, Formatting.None, serializerSettings);

                    var request = new HttpRequestMessage()
                    {
                        RequestUri = new Uri(_BaseAddress + url)
                    };

                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            request.Headers.Add(header.Item1, header.Item2);
                        }
                    }

                    switch (verb)
                    {
                    default:
                    case HttpVerb.GET:
                        request.Method = HttpMethod.Get;
                        break;

                    case HttpVerb.PUT:
                        request.Method  = HttpMethod.Put;
                        request.Content = new StringContent(serializedData, System.Text.Encoding.UTF8, "application/json");
                        break;

                    case HttpVerb.POST:
                        request.Method  = HttpMethod.Post;
                        request.Content = new StringContent(serializedData, System.Text.Encoding.UTF8, "application/json");
                        break;

                    case HttpVerb.DELETE:
                        request.Method = HttpMethod.Delete;
                        break;
                    }

                    response = await this._HttpClient.SendAsync(request);

                    var statusCode = response.StatusCode;

                    if (statusCode == HttpStatusCode.OK)
                    {
                        try
                        {
                            var responseBody = await response.Content.ReadAsStringAsync();

                            if (deserializeAsJson)
                            {
                                var jsonReponseBody = JsonConvert.DeserializeObject(responseBody).ToString();

                                return(JsonConvert.DeserializeObject <TResult>(jsonReponseBody));
                            }
                            else
                            {
                                return((TResult)Convert.ChangeType(responseBody, typeof(TResult)));;
                            }
                        }
                        catch (Exception e)
                        {
                            throw;
                        }
                    }

                    if (statusCode.Equals(HttpStatusCode.InternalServerError) || statusCode.Equals(HttpStatusCode.ServiceUnavailable) || statusCode.Equals((HttpStatusCode)429)) // .NET doesn't have a const for this
                    {
                        var responseJson = await response.Content.ReadAsStringAsync();

                        dynamic result = JsonConvert.DeserializeObject(responseJson);

                        // did we hit an error that we should retry?
                        int code = result["errorCode"];

                        if (code == 4001)
                        {
                            // service may be down temporarily
                            _WaitTime = Backoff(_WaitTime, 60 * 1000);
                        }
                        else if (code == 4002 || code == 4004)
                        {
                            // internal error or simultaneous update.
                            _WaitTime = Backoff(_WaitTime, 1 * 1000);
                        }
                        else if (code == 4003)
                        {
                            // rate limit
                            _WaitTime = Backoff(_WaitTime, 2 * 1000);
                        }
                    }
                    else
                    {
                        _RetryRequest = false;
                        dynamic result;
                        try
                        {
                            var responseJson = await response.Content.ReadAsStringAsync();

                            result = JsonConvert.DeserializeObject(responseJson);
                        }
                        catch (Exception)
                        {
                            throw new Exception(string.Format("HTTP Error {0}: url:[{1}]", statusCode, url));
                        }

                        var message = string.Format("Smartsheet error code {0}: {1} url:[{2}]", result["errorCode"], result["message"], url);

                        throw new Exception(message);
                    }
                }
                catch (Exception e)
                {
                    if (!_RetryRequest)
                    {
                        throw e;
                    }
                }

                _RetryCount += 1;
            }

            throw new Exception(string.Format("Retries exceeded.  url:[{0}]", url));
        }
예제 #23
0
 internal RoutePipelineBuilder(CommandRouteBuilder commandRouteBuilder, HttpVerb verb, string routeTemplate)
 {
     CommandRouteBuilder = commandRouteBuilder;
     Verb          = verb;
     RouteTemplate = routeTemplate;
 }
예제 #24
0
 /// <summary>
 /// Used to specify Http verb of the action.
 /// </summary>
 /// <param name="verb">Http very</param>
 /// <returns>Action builder</returns>
 public IApiControllerActionBuilder <T> WithVerb(HttpVerb verb)
 {
     _verb = verb;
     return(this);
 }
예제 #25
0
 private bool IsCreateOrUpdate(HttpVerb verb)
 {
     return(verb.IsUpdateVerb() || verb == HttpVerb.Post);
 }
예제 #26
0
 public RestClient()
 {
     EndPoint   = string.Empty;
     HttpMethod = HttpVerb.GET;
 }
예제 #27
0
        /// <summary>
        ///     Makes a request to the specified Uri, only if it hasn't exceeded the call limit
        /// </summary>
        /// <param name="endpoint">Endpoint to request</param>
        /// <param name="verb"></param>
        /// <returns></returns>
        private static async Task <HttpResponseMessage> CreateRequest(Uri endpoint, HttpVerb verb = HttpVerb.GET)
        {
            Task <HttpResponseMessage> task = null;

            if (RateLimitingEnabled)
            {
                await _rateSemaphore.WaitAsync();

                if (Stopwatch.Elapsed.Seconds >= SecondsLimit || _rateSemaphore.CurrentCount == 0 ||
                    _concurrentRequests == _limit)
                {
                    var seconds = (SecondsLimit - Stopwatch.Elapsed.Seconds) * 1000;
                    var sleep   = seconds > 0 ? seconds : seconds * -1;
                    Thread.Sleep(sleep);
                    _concurrentRequests = 0;
                    Stopwatch.Restart();
                }

                ++_concurrentRequests;
            }

            var taskFunction = new Func <Task <HttpResponseMessage>, Task <HttpResponseMessage> >(t =>
            {
                if (!RateLimitingEnabled)
                {
                    return(t);
                }
                _rateSemaphore.Release();
                if (_rateSemaphore.CurrentCount != _limit || Stopwatch.Elapsed.Seconds < SecondsLimit)
                {
                    return(t);
                }
                Stopwatch.Restart();
                --_concurrentRequests;
                return(t);
            });

            switch (verb)
            {
            case HttpVerb.GET:
                task = await HttpClient.GetAsync(endpoint)
                       .ContinueWith(taskFunction);

                break;

            case HttpVerb.POST:
                task = await HttpClient.PostAsync(endpoint, null)
                       .ContinueWith(taskFunction);

                break;

            case HttpVerb.DELETE:
                task = await HttpClient.DeleteAsync(endpoint)
                       .ContinueWith(taskFunction);

                break;

            case HttpVerb.PUT:
                task = await HttpClient.PutAsync(endpoint, null)
                       .ContinueWith(taskFunction);

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(verb), verb, null);
            }

            return(await task);
        }
예제 #28
0
 public void SendAdminHttpRequest(HttpVerb method, string path)
 {
     _adminHttpClient.SendAdminHttpRequest(method, path);
 }
        internal static DataServiceProtocolVersion GetDataServiceVersion(HttpVerb verb, string preferHeader)
        {
            var version = DataServiceProtocolVersion.V4;
            if (verb == HttpVerb.Patch || preferHeader != null)
            {
                version = version.IncreaseVersionIfRequired(DataServiceProtocolVersion.V4);
            }

            return version;
        }
예제 #30
0
 /// <summary>
 /// 通过指定多个谓词来限制控制器或操作方法可接受的 HTTP 请求的类型
 /// </summary>
 /// <param name="allow"></param>
 public HttpMethodAttribute(HttpVerb allow)
 {
     this._Allow = allow;
 }
예제 #31
0
        private async Task <WebApiResponse <TOutput> > GetHttpResponse <TOutput, TInput>(HttpVerb verb, string endPoint, TInput input, bool throwException = false)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_baseAddress);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                StringContent content = null;
                // HTTP POST
                HttpResponseMessage response = null;

                switch (verb)
                {
                case HttpVerb.Get:
                    response = await client.GetAsync(endPoint);

                    break;

                case HttpVerb.Post:
                    content  = new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, "application/json");
                    response = await client.PostAsync(endPoint, content);

                    break;

                case HttpVerb.Put:
                    content  = new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, "application/json");
                    response = await client.PutAsync(endPoint, content);

                    break;

                case HttpVerb.Delete:
                    response = await client.DeleteAsync(endPoint);

                    break;

                default:
                    break;
                }

                //response.EnsureSuccessStatusCode();
                string data = await response.Content.ReadAsStringAsync();

                var result = new WebApiResponse <TOutput>();
                result.IsSucceded = response.IsSuccessStatusCode;
                result.StatusCode = response.StatusCode;

                try
                {
                    var serializeOptions = new JsonSerializerOptions
                    {
                        PropertyNamingPolicy        = JsonNamingPolicy.CamelCase,
                        PropertyNameCaseInsensitive = true
                    };
                    result.Response = JsonSerializer.Deserialize <TOutput>(data, serializeOptions);
                }
                catch (Exception ex)
                {
                    // ignored
                }

                if (!response.IsSuccessStatusCode)
                {
                    SerializableError err = null;
                    try
                    {
                        err = JsonSerializer.Deserialize <SerializableError>(data);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    if (err?.Any() == true)
                    {
                        var message = err.First().Value.ToString();
                        if (throwException)
                        {
                            var ex = new Exception(message);
                            foreach (var item in err)
                            {
                                if (!ex.Data.Contains(item.Key))
                                {
                                    ex.Data.Add(item.Key, item.Value);
                                }
                            }
                            throw ex;
                        }
                        else
                        {
                            result.Message = message;
                            result.Errors  = new List <ErrorItem>();

                            foreach (var item in err)
                            {
                                if (result.Errors.All(x => x.Key != item.Key))
                                {
                                    result.Errors.Add(new ErrorItem
                                    {
                                        Key   = item.Key,
                                        Value = Convert.ToString(item.Value)
                                    });
                                }
                            }
                        }
                    }
                }

                return(result);
            }
        }
예제 #32
0
 public void Open(HttpVerb verb, string url, bool @async, string userName, string password)
 {
 }
예제 #33
0
 /// <summary>
 /// Returns the verb of the request: GET, POST, PUT, DELETE, and so forth.
 /// </summary>
 public static HttpVerb Verb(this HttpListenerContext context)
 {
     return(HttpVerb.Create(context.Request.HttpMethod.ToUpper()));
 }
예제 #34
0
        [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]         // http://stackoverflow.com/questions/3831676/ca2202-how-to-solve-this-case
        public string MakeRequest(string target, HttpVerb method = HttpVerb.Get, Dictionary <string, string> parameters = null, string data = null)
        {
            if ((parameters != null) && parameters.Any())
            {
                target += "?";

                // Append all URL parameters
                parameters.Aggregate(target, (current, parameter) => current + string.Format("{0}={1}", parameter.Key, parameter.Value));
            }

            var request = (HttpWebRequest)WebRequest.Create(target);

            // Set request header
            request.Method        = method.ToString().ToUpper();
            request.ContentLength = 0;
            request.ContentType   = "text\\xml";

            if (target.Contains("https://"))
            {
                request.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
                {
                    return(certificate.Equals(Certificate));
                };
            }

            // Set authorization header
            var credentials = Convert.ToBase64String(Encoding.GetBytes(string.Format("{0}:{1}", UserName, Password)));

            request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + credentials);

            // Append post data
            if (!string.IsNullOrEmpty(data) && ((method == HttpVerb.Post) || (method == HttpVerb.Put)))
            {
                var bytes = Encoding.GetBytes(data);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            // Make request
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }

            RequestCounter++;

            if (response != null)
            {
                switch (response.StatusCode)
                {
                case HttpStatusCode.Created:
                case HttpStatusCode.OK:
                    // Read the response
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream))
                            {
                                return(reader.ReadToEnd());
                            }
                        }
                    }
                    break;

                case HttpStatusCode.BadRequest:
                    // Build error string
                    var error = new StringBuilder();
                    error.AppendLine("Bad request. The data was: " + data);
                    throw new InvalidOperationException(error.ToString());

                case HttpStatusCode.NotFound:
                    throw new InstanceNotFoundException("Object doesn't exist.");

                default:
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }
            }

            return(null);
        }
예제 #35
0
 public void SendAdminHttpRequest <T>(HttpVerb method, string path, T requestContent, IDictionary <string, string> headers = null) where T : class
 {
     _adminHttpClient.SendAdminHttpRequest(method, path, requestContent, headers);
 }
예제 #36
0
 /// <summary>
 /// Returns the http method string for the given verb
 /// </summary>
 /// <param name="verb">The verb to get the http method for</param>
 /// <returns>The http method string (the name of the verb, all uppercase)</returns>
 public static string ToHttpMethod(this HttpVerb verb)
 {
     return(verb.ToString().ToUpperInvariant());
 }
예제 #37
0
 public void Open(HttpVerb verb, string url, bool @async)
 {
 }
예제 #38
0
 /// <summary>
 /// Returns the http method string for the given verb
 /// </summary>
 /// <param name="verb">The verb to get the http method for</param>
 /// <returns>The http method string (the name of the verb, all uppercase)</returns>
 public static bool IsUpdateVerb(this HttpVerb verb)
 {
     return(verb == HttpVerb.Patch || verb == HttpVerb.Put);
 }
예제 #39
0
 public void Open(HttpVerb verb, string url)
 {
 }
예제 #40
0
 public MvcControllerActionInfo(string actionName, HttpVerb verb, MethodInfo method, IFilter[] filters = null, bool?isApiExplorerEnabled = null) : base(actionName, method, filters, isApiExplorerEnabled)
 {
     this.Verb = verb;
 }
예제 #41
0
        public static void ExecuteUri(this DataServiceContext context, IAsyncContinuation continuation, bool async, Uri requestUri, HttpVerb verb, OperationParameter[] inputParameters, Action <OperationResponse> onCompletion)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");
            ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation");
            ExceptionUtilities.CheckArgumentNotNull(onCompletion, "onCompletion");

            string method = Enum.GetName(typeof(HttpVerb), verb).ToUpperInvariant();

            AsyncHelpers.InvokeSyncOrAsyncMethodCall <OperationResponse>(
                continuation,
                async,
                () => context.Execute(requestUri, method, inputParameters),
                c => context.BeginExecute(requestUri, c, null, method, inputParameters),
                r => context.EndExecute(r),
                onCompletion);
        }
예제 #42
0
        /// <summary>
        /// Get presigned url for requested operation with Blob Storage.
        /// </summary>
        public async Task <string> GetPresignedUrlAsync(string fullPath, string mimeType, int expiresInSeconds, HttpVerb verb)
        {
            IAmazonS3 client = await GetClientAsync();

            return(client.GetPreSignedURL(new GetPreSignedUrlRequest()
            {
                BucketName = _bucketName,
                ContentType = mimeType,
                Expires = DateTime.UtcNow.AddSeconds(expiresInSeconds),
                Key = StoragePath.Normalize(fullPath, false),
                Verb = verb,
            }));
        }
예제 #43
0
 /// <summary>
 /// Sets up the HttpContext objects to simulate a request.
 /// </summary>
 /// <param name="url"></param>
 /// <param name="httpVerb"></param>
 /// <param name="headers"></param>
 public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection headers)
 {
     return(SimulateRequest(url, httpVerb, null, headers));
 }
예제 #44
0
        private HttpWebRequest CreateRequest()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);

            req.AllowAutoRedirect = false;
            req.CookieContainer   = new CookieContainer();
            req.Headers.Add("Accept-Language", defaultLanguage);
            req.Accept    = accept;
            req.UserAgent = userAgent;
            req.KeepAlive = true;

            if (context.Cookies != null)
            {
                req.CookieContainer.Add(context.Cookies);
            }
            if (!string.IsNullOrEmpty(context.Referer))
            {
                req.Referer = context.Referer;
            }

            if (verb == HttpVerb.HEAD)
            {
                req.Method = "HEAD";
                return(req);
            }

            if (postingData.Count > 0 || files.Count > 0)
            {
                verb = HttpVerb.POST;
            }

            if (verb == HttpVerb.POST)
            {
                req.Method = "POST";

                MemoryStream memoryStream = new MemoryStream();
                StreamWriter writer       = new StreamWriter(memoryStream);

                if (files.Count > 0)
                {
                    string newLine  = "\r\n";
                    string boundary = Guid.NewGuid().ToString().Replace("-", "");
                    req.ContentType = "multipart/form-data; boundary=" + boundary;

                    foreach (string key in postingData.Keys)
                    {
                        writer.Write("--" + boundary + newLine);
                        writer.Write("Content-Disposition: form-data; name=\"{0}\"{1}{1}", key, newLine);
                        writer.Write(postingData[key] + newLine);
                    }

                    foreach (HttpUploadingFile file in files)
                    {
                        writer.Write("--" + boundary + newLine);
                        writer.Write(
                            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}",
                            file.FieldName,
                            file.FileName,
                            newLine
                            );
                        writer.Write("Content-Type: application/octet-stream" + newLine + newLine);
                        writer.Flush();
                        memoryStream.Write(file.Data, 0, file.Data.Length);
                        writer.Write(newLine);
                        writer.Write("--" + boundary + newLine);
                    }
                }
                else
                {
                    req.ContentType = "application/x-www-form-urlencoded";
                    StringBuilder sb = new StringBuilder();
                    foreach (string key in postingData.Keys)
                    {
                        sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(postingData[key]));
                    }
                    if (sb.Length > 0)
                    {
                        sb.Length--;
                    }
                    writer.Write(sb.ToString());
                }

                writer.Flush();

                using (Stream stream = req.GetRequestStream()) {
                    memoryStream.WriteTo(stream);
                }
            }

            if (startPoint != 0 && endPoint != 0)
            {
                req.AddRange(startPoint, endPoint);
            }
            else if (startPoint != 0 && endPoint == 0)
            {
                req.AddRange(startPoint);
            }

            return(req);
        }
예제 #45
0
 /// <summary>
 /// Sets up the HttpContext objects to simulate a request.
 /// </summary>
 /// <param name="url"></param>
 /// <param name="httpVerb"></param>
 public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb)
 {
     return(SimulateRequest(url, httpVerb, null, null));
 }
예제 #46
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);
        }
 /// <summary>
 /// Sets the Verb property for this request.
 /// Specifies which verb to use in the pre-signed URL.
 /// Accepted verbs are GET, PUT and HEAD.
 /// Default value is GET.
 /// </summary>
 /// <param name="verb">The value that Verb is set to</param>
 /// <returns>the response with the Verb set</returns>
 public GetPreSignedUrlRequest WithVerb(HttpVerb verb)
 {
     Verb = verb;
     return this;
 }
예제 #48
0
 /// <summary>
 /// Sets up the HttpContext objects to simulate a request.
 /// </summary>
 /// <param name="url"></param>
 /// <param name="httpVerb"></param>
 /// <param name="headers"></param>
 public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection headers)
 {
     return SimulateRequest(url, httpVerb, null, headers);
 }
예제 #49
0
 public ReadQuery(HttpVerb HttpVerb, FhirVersion FhirVersion, Uri RequestUri, Dictionary <string, StringValues> RequestQuery, Dictionary <string, StringValues> HeaderDictionary, string ResourceName, string ResourceId)
     : base(HttpVerb, FhirVersion, RequestUri, RequestQuery, HeaderDictionary, ResourceName, ResourceId)
 {
 }
예제 #50
0
 /// <summary>
 /// Sets up the HttpContext objects to simulate a request.
 /// </summary>
 /// <param name="url"></param>
 /// <param name="httpVerb"></param>
 public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb)
 {
     return SimulateRequest(url, httpVerb, null, null);
 }
예제 #51
0
 /// <summary>
 /// Used to specify Http verb of the action.
 /// </summary>
 /// <param name="verb">Http very</param>
 /// <returns>Action builder</returns>
 public IDefaultControllerActionBuilder <T> WithVerb(HttpVerb verb)
 {
     Verb = verb;
     return(this);
 }
예제 #52
0
 public WebPage Submit(Uri url, HttpVerb verb)
 {
     return(browser.NavigateToPage(url, verb, SerializeFormFields()));
 }
예제 #53
0
 public GetPreSignedUrlRequest WithVerb(HttpVerb verb)
 {
     this.Verb = verb;
     return(this);
 }
예제 #54
0
 public static void AssertCorrectMethod(this IRequest request, HttpVerb method)
 {
     Assert.That(request.Method, Is.EqualTo(method));
 }
예제 #55
0
 public Link(string rel, string href, HttpVerb method)
 {
     Rel = rel;
     Href = href;
     Method = method;
 }
예제 #56
0
 public void AllowMethod(HttpVerb verb, string resource, ICollection <Condition> conditions = null)
 {
     AddMethod(Effect.Allow, verb, resource, conditions);
 }
예제 #57
0
        /// <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;
        }
예제 #58
0
        private byte[] StreamFrom(Uri url, HttpVerb httpVerb, Dictionary <string, string> args)
        {
            if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
            {
                url = new Uri(url.ToString() + EncodeDictionary(args, true));
            }

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.AllowWriteStreamBuffering = false;
            request.Method = httpVerb.ToString();

            if (httpVerb == HttpVerb.POST)
            {
                string postData = EncodeDictionary(args, false);

                ASCIIEncoding encoding      = new ASCIIEncoding();
                byte[]        postDataBytes = encoding.GetBytes(postData);

                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = postDataBytes.Length;

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

            try
            {
                byte[] result = null;
                byte[] buffer = new byte[1024];

                using (HttpWebResponse response
                           = request.GetResponse() as HttpWebResponse)
                {
                    using (Stream requestStream = response.GetResponseStream())
                    {
                        int dataLenght = (int)response.ContentLength;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            while (result == null)
                            {
                                int bytesRead = requestStream.Read(buffer, 0, buffer.Length);
                                if (bytesRead == 0)
                                {
                                    result = ms.ToArray();
                                }
                                else
                                {
                                    ms.Write(buffer, 0, bytesRead);
                                }
                            }
                        }
                    }
                }
                return(result);
            }
            catch
            {
                throw;
            }
        }
예제 #59
0
        internal static double[] MapImageCoordinatatesInternal(string imageFieldName, HttpVerb verb, NameValueCollection queryString, NameValueCollection form) {
            // Select collection where to look according to verb

            NameValueCollection c = null;

            switch (verb) {
                case HttpVerb.GET:
                case HttpVerb.HEAD:
                    c = queryString;
                    break;

                case HttpVerb.POST:
                    c = form;
                    break;

                default:
                    return null;
            }

            // Look for .x and .y values in the collection

            double[] ret = null;

            try {
                string x = c[imageFieldName + ".x"];
                string y = c[imageFieldName + ".y"];

                double xVal;
                double yVal;

                if (x != null && y != null && HttpUtility.TryParseCoordinates(x, out xVal) && HttpUtility.TryParseCoordinates(y, out yVal)) {
                    ret = new[] { xVal, yVal };
                }
            }
            catch {
                // eat parsing exceptions
            }

            return ret;
        }
예제 #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RouteAttribute"/> class.
 /// </summary>
 /// <param name="isBaseRoute"><see langword="true"/> if this attribute represents a base route;
 /// <see langword="false"/> (the default) if it represents a terminal (non-base) route.</param>
 /// <param name="verb">The verb.</param>
 /// <param name="route">The route.</param>
 /// <exception cref="ArgumentNullException"><paramref name="route"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException">
 /// <para><paramref name="route"/> is empty.</para>
 /// <para>- or -</para>
 /// <para><paramref name="route"/> does not start with a slash (<c>/</c>) character.</para>
 /// <para>- or -</para>
 /// <para><paramref name="route"/> does not comply with route syntax.</para>
 /// </exception>
 /// <seealso cref="Routing.Route.IsValid"/>
 public RouteAttribute(HttpVerb verb, string route, bool isBaseRoute = false)
 {
     Matcher = RouteMatcher.Parse(route, isBaseRoute);
     Verb    = verb;
 }