Exemplo n.º 1
0
        private static string GetHttpVerb(RouteAction action)
        {
            HttpVerbs verb = HttpVerbs.Get;

            switch (action)
            {
            case RouteAction.CREATE:
                verb = HttpVerbs.Post;
                break;

            case RouteAction.UPDATE:
                verb = HttpVerbs.Put;
                break;

            case RouteAction.DELETE:
                verb = HttpVerbs.Delete;
                break;

            case RouteAction.LIST:
            case RouteAction.SHOW:
            case RouteAction.SEARCH:
                verb = HttpVerbs.Get;
                break;

            default:
                verb = HttpVerbs.Get;
                break;
            }
            return(verb.ToString());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TestHttpRequest" /> class.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="httpMethod">The HTTP method.</param>
        public TestHttpRequest(string url, HttpVerbs httpMethod = HttpVerbs.Get)
        {
            RawUrl = url ?? throw new ArgumentNullException(nameof(url));

            HttpMethod = httpMethod.ToString();
            Url        = new Uri(url);
        }
Exemplo n.º 3
0
        protected virtual HttpWebRequest GetRequest(string uri, HttpVerbs verb)
        {
            HttpWebRequest request = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);

                if (RequestTimeoutInMilliseconds.HasValue)
                {
                    request.Timeout = RequestTimeoutInMilliseconds.Value;
                }

                request.Headers.Clear();
                Headers?.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
                CustomHeaders?.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));

                request.Referer = BaseUrl;
                request.Method  = verb.ToString().ToUpper();

                request.ContentType = ContentType;
                request.Accept      = ContentType;

                return(request);
            }
            catch (Exception ex)
            {
                request?.Abort();

                log.Error(ex.Message, ex);
                throw;
            }
        }
Exemplo n.º 4
0
        // CODEREVIEW: this implementation kind of misses the point of HttpVerbs
        // by falling back to string comparison, consider something better
        // also, how do we keep this switch in sync?
        public static bool IsHttpMethod(this HttpRequestBase request, HttpVerbs httpMethod, bool allowOverride)
        {
            switch (httpMethod)
            {
            case HttpVerbs.Get:
                return(request.IsHttpMethod("GET", allowOverride));

            case HttpVerbs.Post:
                return(request.IsHttpMethod("POST", allowOverride));

            case HttpVerbs.Put:
                return(request.IsHttpMethod("PUT", allowOverride));

            case HttpVerbs.Delete:
                return(request.IsHttpMethod("DELETE", allowOverride));

            case HttpVerbs.Head:
                return(request.IsHttpMethod("HEAD", allowOverride));

            case HttpVerbs.Patch:
                return(request.IsHttpMethod("PATCH", allowOverride));

            case HttpVerbs.Options:
                return(request.IsHttpMethod("OPTIONS", allowOverride));

            default:
                // CODEREVIEW: does this look reasonable?
                return(request.IsHttpMethod(httpMethod.ToString().ToUpperInvariant(), allowOverride));
            }
        }
        public RemoteValidator(string errorMessage,
                               string action,
                               string controller,
                               HttpVerbs HttpVerb      = HttpVerbs.Get,
                               string additionalFields = "")
            : base(errorMessage)
        {
            var httpContext = HttpContext.Current;

            if (httpContext == null)
            {
                var request  = new HttpRequest("/", Common.GetValueFromConfig("DefaultHttpRequestUrl"), "");
                var response = new HttpResponse(new StringWriter());
                httpContext = new HttpContext(request, response);
            }

            var httpContextBase = new HttpContextWrapper(httpContext);
            var routeData       = new RouteData();
            var requestContext  = new RequestContext(httpContextBase, routeData);

            var helper = new UrlHelper(requestContext);

            Url              = helper.Action(action, controller);
            HttpMethod       = HttpVerb.ToString();
            AdditionalFields = additionalFields;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets access token for user
        /// </summary>
        /// <returns>access token</returns>


        private async Task <HttpResponseMessage> SendRequest(HttpVerbs action, string url, object inputModel = null, bool requiresAuthentication = false)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_resourceUrl);
                client.Timeout     = TimeSpan.FromSeconds(30);

                if (requiresAuthentication)
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenResponse.AccessToken);
                }
                HttpResponseMessage response = null;
                try
                {
                    switch (action)
                    {
                    case HttpVerbs.Get:
                        response = await client.GetAsync(url);

                        break;

                    case HttpVerbs.Post:
                        var postContent = inputModel.ToHttpContent();
                        response = await client.PostAsync(url, postContent);

                        break;

                    case HttpVerbs.Put:
                        var putContent = inputModel.ToHttpContent();
                        response = await client.PutAsync(url, putContent);

                        break;

                    case HttpVerbs.Delete:
                        response = await client.DeleteAsync(url);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    response = null;
                }

                if (response == null)
                {
                    Console.WriteLine("Cannot get response from server.");
                    return(response);
                }

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Console.WriteLine($"Token is unauthorized to do this action: [{action.ToString().ToUpper()}] /{url}. Please check your bearer token in request header.");
                }

                return(response);
            }
        }
Exemplo n.º 7
0
        public RequestResult ProcessRequest(string url, HttpVerbs httpVerb, NameValueCollection formValues, NameValueCollection headers)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (httpVerb == HttpVerbs.Post && headers == null)
            {
                headers = new NameValueCollection();
                headers.Add("content-type", "application/x-www-form-urlencoded");
            }
            else if (httpVerb == HttpVerbs.Post && headers != null)
            {
                if (string.IsNullOrEmpty(headers["content-type"]))
                {
                    headers.Add("content-type", "application/x-www-form-urlencoded");
                }
            }

            // Fix up URLs that incorrectly start with / or ~/
            if (url.StartsWith("~/"))
            {
                url = url.Substring(2);
            }
            else if (url.StartsWith("/"))
            {
                url = url.Substring(1);
            }

            // Parse out the querystring if provided
            string query = "";
            int    querySeparatorIndex = url.IndexOf("?");

            if (querySeparatorIndex >= 0)
            {
                query = url.Substring(querySeparatorIndex + 1);
                url   = url.Substring(0, querySeparatorIndex);
            }

            // Perform the request
            LastRequestData.Reset();
            var    output        = new StringWriter();
            string httpVerbName  = httpVerb.ToString().ToLower();
            var    workerRequest = new SimulatedWorkerRequest(url, query, output, Cookies, httpVerbName, formValues, headers);

            HttpRuntime.ProcessRequest(workerRequest);

            // Capture the output
            AddAnyNewCookiesToCookieCollection();
            Session = LastRequestData.HttpSessionState;
            return(new RequestResult
            {
                ResponseText = output.ToString(),
                ActionExecutedContext = LastRequestData.ActionExecutedContext,
                ResultExecutedContext = LastRequestData.ResultExecutedContext,
                Response = LastRequestData.Response,
            });
        }
Exemplo n.º 8
0
        private async Task <HttpResponseMessage> SendRequest(HttpVerbs action, string url, object inputModel = null, bool requiresAuthentication = false)
        {
            HttpResponseMessage response = null;

            using (var client = new HttpClient {
                BaseAddress = new Uri(_resourceUrl), Timeout = TimeSpan.FromSeconds(30)
            })
            {
                if (requiresAuthentication)
                {
                    client.DefaultRequestHeaders.Add("X-PCK", _publicKey);
                    var stamp = GetStamp();
                    client.DefaultRequestHeaders.Add("X-Stamp", stamp.ToString(CultureInfo.InvariantCulture));
                    var signature = GetSignature(stamp);
                    client.DefaultRequestHeaders.Add("X-Signature", signature);
                }

                try
                {
                    switch (action)
                    {
                    case HttpVerbs.Post:
                        var postContent = inputModel.ToHttpContent();
                        response = await client.PostAsync(url, postContent);

                        break;

                    case HttpVerbs.Get:
                        response = await client.GetAsync(url);

                        break;

                    case HttpVerbs.Delete:
                        response = await client.DeleteAsync(url);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    response = null;
                }

                if (response == null)
                {
                    Console.WriteLine("Cannot get response from server.");
                    return(null);
                }

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Console.WriteLine($"Token is unauthorized to do this action: [{action.ToString().ToUpper()}] /{url}. Please check your bearer token in request header.");
                }

                return(response);
            }
        }
Exemplo n.º 9
0
        private static async Task <HttpResponseMessage> RunHttpClientWithMethodAsync(HttpClient client, HttpVerbs verb, Uri uri, HttpContent param)
        {
            try
            {
                Debug.WriteLine("HttpClient " + verb.ToString() + ": " + uri.ToString());
                HttpResponseMessage response = null;

                switch (verb)
                {
                case HttpVerbs.GET:
                    response = await client.GetAsync(uri);

                    break;

                case HttpVerbs.POST:
                    response = await client.PostAsync(uri, param);

                    break;

                case HttpVerbs.PUT:
                    response = await client.PutAsync(uri, param);

                    break;

                case HttpVerbs.DELETE:
                    if (param != null)
                    {
                        HttpRequestMessage req = new HttpRequestMessage()
                        {
                            Content    = param,
                            Method     = HttpMethod.Delete,
                            RequestUri = uri
                        };
                        response = await client.SendAsync(req);
                    }
                    else
                    {
                        response = await client.DeleteAsync(uri);
                    }
                    break;

                default:
                    break;
                }

                return(response);
            }
            catch (Exception e)
            {
                Debug.WriteLine("ERROR: " + e.InnerException.Message);
                throw e;
            }
        }
Exemplo n.º 10
0
        public RequestResult ProcessRequest(
            string url,
            HttpVerbs httpVerb,
            NameValueCollection formValues,
            NameValueCollection headers)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            // Fix up URLs that incorrectly start with / or ~/
            if (url.StartsWith("~/"))
            {
                url = url.Substring(2);
            }

            else if (url.StartsWith("/"))
            {
                url = url.Substring(1);
            }

            // Parse out the querystring if provided
            var query = "";
            var querySeparatorIndex = url.IndexOf("?", StringComparison.Ordinal);

            if (querySeparatorIndex >= 0)
            {
                query = url.Substring(querySeparatorIndex + 1);
                url   = url.Substring(0, querySeparatorIndex);
            }

            // Perform the request
            LastRequestData.Reset();
            var output        = new StringWriter();
            var httpVerbName  = httpVerb.ToString().ToLower();
            var workerRequest = new VirtualedWorkerRequest(url, query, httpVerbName, Cookies, formValues, headers, output);

            HttpRuntime.ProcessRequest(workerRequest);

            // Capture the output
            AddAnyNewCookiesToCookieCollection();
            Session = LastRequestData.HttpSessionState;

            return(new RequestResult
            {
                ResponseText = output.ToString(),
                ActionExecutedContext = LastRequestData.ActionExecutedContext,
                ResultExecutedContext = LastRequestData.ResultExecutedContext,
                Response = LastRequestData.Response,
            });
        }
Exemplo n.º 11
0
        public static string ExternalHttpRequest(string requestUriString, HttpVerbs verb, int timeout = 600000, bool streamResult = true)
        {
            var request = WebRequest.Create(requestUriString);

            request.Method  = verb.ToString();
            request.Timeout = timeout;
            if (verb == HttpVerbs.POST)
            {
                request.ContentLength = 0;
            }

            return(GetResponse(request, streamResult));
        }
        private RequestResult ProcessRequest(string url, HttpVerbs httpVerb, byte[] bodyData, NameValueCollection headers)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            // Fix up URLs that incorrectly start with / or ~/
            if (url.StartsWith("~/"))
            {
                url = url.Substring(2);
            }
            else if (url.StartsWith("/"))
            {
                url = url.Substring(1);
            }

            // Parse out the querystring if provided
            string query = "";
            int    querySeparatorIndex = url.IndexOf("?", StringComparison.Ordinal);

            if (querySeparatorIndex >= 0)
            {
                query = url.Substring(querySeparatorIndex + 1);
                url   = url.Substring(0, querySeparatorIndex);
            }

            // Perform the request
            LastRequestData.Reset();
            var    output        = new StringWriter();
            string httpVerbName  = httpVerb.ToString().ToUpperInvariant();
            var    workerRequest = new SimulatedWorkerRequest(url, query, output, Cookies, httpVerbName, bodyData, headers);

            HttpRuntime.ProcessRequest(workerRequest);

            // Capture the output
            AddAnyNewCookiesToCookieCollection();
            Session = LastRequestData.HttpSessionState;

            // In the case of errors, try to pull out some useful info from the HttpContext
            var response = LastRequestData.Response ??
                           RecoverResponseData(LastRequestData.ActionExecutedContext, workerRequest);

            return(new RequestResult
            {
                ResponseText = output.ToString(),
                ActionExecutedContext = LastRequestData.ActionExecutedContext,
                ResultExecutedContext = LastRequestData.ResultExecutedContext,
                Response = response
            });
        }
Exemplo n.º 13
0
        /// <summary>
        /// Request Api - Only JSON
        /// </summary>
        /// <param name="verb"></param>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns>String JSON</returns>
        public static string RequestApi(HttpVerbs verb, string url, string json)
        {
            //Initial Structure
            //var token = BuscarToken();

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = verb.ToString().ToUpper();
            //httpWebRequest.Headers.Add("Authorization", $"Bearer {token.AccessToken}");

            //Param
            if (verb != HttpVerbs.Get)
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    if (!string.IsNullOrEmpty(json))
                    {
                        streamWriter.Write(json);
                    }
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }

            try
            {
                using (var response = httpWebRequest.GetResponse())
                {
                    //Response
                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    if (httpResponse.StatusCode != HttpStatusCode.OK &&
                        httpResponse.StatusCode != HttpStatusCode.Created)
                    {
                        throw new ApiInfoxException(httpResponse.StatusCode, $"Server error (HTTP {httpResponse.StatusCode}: {httpResponse.StatusDescription}).");
                    }

                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        return(streamReader.ReadToEnd());
                    }
                }
            }
            catch (WebException web)
            {
                throw new ApiInfoxException(((HttpWebResponse)web.Response).StatusCode,
                                            $"Server error (HTTP {((HttpWebResponse)web.Response).StatusCode}: {((HttpWebResponse)web.Response).StatusDescription}) - (Web Status {web.Status}: {web.Status.ToDescription()}) - Msg ({web.Message}).");
            }
        }
Exemplo n.º 14
0
        private async Task<HttpResponseMessage> ExecuteRequest(HttpVerbs method, Uri requestUri, HttpContent content = null)
        {
            var request = WebRequest.CreateHttp(requestUri);
            var httpResponseMessage = new HttpResponseMessage();

            request.Headers = DefaultRequestHeaders;
            request.Method = method.ToString();
            request.Accept = "*/*";

            httpResponseMessage.Request = request;

            Logger.LogWebRequest(request);
            if (content != null) Logger.LogVerbose(content.ToString());

            try
            {
                if (method == HttpVerbs.POST)
                {
                    request.ContentType = content.ContentType;

                    var requestStreamTask = Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null);
                    using (Stream stream = await requestStreamTask.ConfigureAwait(false))
                    {
                        content.WriteToStream(stream);
                    }
                }

                var responseTask = Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
                using (var response = await responseTask.ConfigureAwait(false) as HttpWebResponse)
                {
                    httpResponseMessage.SetResponseData(response);
                    Logger.LogWebResponse(response);
                }
            }
            catch (WebException we)
            {
                var response = (HttpWebResponse)we.Response;
                if (response != null)
                    httpResponseMessage.SetResponseData(response);

                Logger.Log(we);
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }

            return httpResponseMessage;
        }
Exemplo n.º 15
0
        public static string ExternalWebRequest(byte[] content, HttpVerbs verb, string requestUriString, int timeout = 600000)
        {
            //Not for GETs
            if (string.Compare("GET", verb.ToString(), StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                throw new ArgumentException("Specified verb not valid for ExternalWebRequest");
            }

            var request = HttpWebRequest.Create(requestUriString);

            request.Method      = verb.ToString();
            request.ContentType = "application/json; charset=utf-8";
            request.Timeout     = timeout;

            if (null != content)
            {
                request.ContentLength = content.Length;
                //request.ContentType = "application/x-www-form-urlencoded";
                request.GetRequestStream().Write(content, 0, content.Length);

                return(GetResponse(request));
            }
            return(null);
        }
        /// <summary>
        ///     Builds a controller of the required type using any data previously supplied (or defaults).
        /// </summary>
        /// <returns>An initialized controller of type <typeparamref name="TController" />.</returns>
        /// <exception cref="SpecificationException">Thrown if the controller cannot be built.</exception>
        public TController Build()
        {
            var dataLoader = new ObjectDataLoader(data);

            UnitOfWork = uowBuilder.WithData(dataLoader).Build();
            var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile <ViewModelMappingProfile>(); });

            mapperConfiguration.AssertConfigurationIsValid();
            Mapper = mapperConfiguration.CreateMapper();
            var notifier = new FakeNotificationService();

            RulesService = new GameRulesService(UnitOfWork, Mapper, notifier);
            HttpContextBase httpContext;

            if (postedFile == null)
            {
                httpContext = new FakeHttpContext(requestPath, requestMethod.ToString("G"));
            }
            else
            {
                var filesCollection = new FakeHttpFileCollection(postedFile);
                httpContext = new FakeHttpContext(requestPath, filesCollection);
            }
            var fakeIdentity  = new FakeIdentity(requestUsername);
            var fakePrincipal = new FakePrincipal(fakeIdentity, requestUserRoles);

            httpContext.User = fakePrincipal;
            var context = new ControllerContext {
                HttpContext = httpContext
            };

            /*
             * Use Ninject to create the controller, as we don't know in advance what
             * type of controller or how many constructor parameters it has.
             */
            var kernel     = BuildNinjectKernel(fakeIdentity, requestUserId, RulesService);
            var controller = kernel.Get <TController>();

            if (controller == null)
            {
                throw new SpecificationException(
                          $"ControllerContextBuilder: Unable to create controller instance of type {nameof(TController)}");
            }

            controller.ControllerContext = context;
            controller.TempData          = tempdata;
            return(controller);
        }
 // CODEREVIEW: this implementation kind of misses the point of HttpVerbs
 // by falling back to string comparison, consider something better
 // also, how do we keep this switch in sync?
 public static bool IsHttpMethod(this HttpRequestBase request, HttpVerbs httpMethod, bool allowOverride) {
     switch (httpMethod) {
         case HttpVerbs.Get:
             return request.IsHttpMethod("GET", allowOverride);
         case HttpVerbs.Post:
             return request.IsHttpMethod("POST", allowOverride);
         case HttpVerbs.Put:
             return request.IsHttpMethod("PUT", allowOverride);
         case HttpVerbs.Delete:
             return request.IsHttpMethod("DELETE", allowOverride);
         case HttpVerbs.Head:
             return request.IsHttpMethod("HEAD", allowOverride);
         default:
             // CODEREVIEW: does this look reasonable?
             return request.IsHttpMethod(httpMethod.ToString().ToUpperInvariant(), allowOverride);
     }
 }
Exemplo n.º 18
0
        /// <summary>
        /// Request Api - Only JSON
        /// </summary>
        /// <param name="verb"></param>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns>String JSON</returns>
        public static string RequestApi(HttpVerbs verb, string url, string json)
        {
            //Initial Structure
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(API_EBANX_URL.TrimEnd('/') + '/' + url.TrimStart('/'));

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = verb.ToString().ToUpper();

            //Param
            if (verb != HttpVerbs.Get)
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    if (!string.IsNullOrEmpty(json))
                    {
                        streamWriter.Write(json);
                    }
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }

            try
            {
                using (var response = httpWebRequest.GetResponse())
                {
                    //Response
                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    if (httpResponse.StatusCode != HttpStatusCode.OK &&
                        httpResponse.StatusCode != HttpStatusCode.Created)
                    {
                        throw new ApiEbanxException(httpResponse.StatusCode, $"Server error (HTTP {httpResponse.StatusCode}: {httpResponse.StatusDescription}).");
                    }

                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        return(streamReader.ReadToEnd());
                    }
                }
            }
            catch (WebException web)
            {
                throw new ApiEbanxException(((HttpWebResponse)web.Response).StatusCode,
                                            $"Server error (HTTP {((HttpWebResponse)web.Response).StatusCode}: {((HttpWebResponse)web.Response).StatusDescription}) - (Web Status {web.Status}: {web.Status.ToDescription()}) - Msg ({web.Message}).");
            }
        }
Exemplo n.º 19
0
        public static IHtmlString AsyncPartialLoader(this HtmlHelper helper, string actionName, string controllerName,
                                                     RouteValueDictionary routeValueDictionary = null,
                                                     HttpVerbs verb = HttpVerbs.Get)
        {
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            var tagBuilder = new TagBuilder("partial-loader");

            tagBuilder.MergeAttribute("data-url", urlHelper.Action(actionName, controllerName, routeValueDictionary));
            tagBuilder.MergeAttribute("data-verb", verb.ToString());

            var loadingImageTagBuilder = new TagBuilder("img");

            loadingImageTagBuilder.MergeAttribute("src", "/Images/loading.gif");
            tagBuilder.InnerHtml = loadingImageTagBuilder.ToString(TagRenderMode.SelfClosing);

            return(new MvcHtmlString(tagBuilder.ToString()));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Determines whether the URL parameter contains a valid value for this constraint.
        /// </summary>
        /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
        /// <param name="route">The object that this constraint belongs to.</param>
        /// <param name="parameterName">The name of the parameter that is being checked.</param>
        /// <param name="values">An object that contains the parameters for the URL.</param>
        /// <param name="routeDirection">An object that indicates whether the constraint check is being performed when an incoming request is being handled or when a URL is being generated.</param>
        /// <returns>
        /// true if the URL parameter contains a valid value; otherwise, false.
        /// </returns>
        public bool Match(HttpContextBase httpContext, Route route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var isMatch = true;

            if (routeDirection == RouteDirection.IncomingRequest)
            {
                var httpMethod         = httpContext.Request.HttpMethod;
                var httpMethodOverride = httpContext.Request.Form[HttpVerbFormKey];
                if (!String.IsNullOrEmpty(httpMethodOverride))
                {
                    httpMethod = httpMethodOverride;
                }

                isMatch = verbs.ToString().ToUpperInvariant().Equals(httpMethod);
            }

            return(isMatch);
        }
Exemplo n.º 21
0
        public static void LogExtServiceCallDetails(string clientHeader, HttpVerbs?requestType, string serviceName,
                                                    string methodName, string requestObj, string responseObj, int elapsedTime, bool hasPassword = false)
        {
            try
            {
                if (IsEnableExtServiceLog)
                {
                    Task.Factory.StartNew(
                        () =>
                    {
                        try
                        {
                            ExtServiceLogs logData = new ExtServiceLogs()
                            {
                                requestType = requestType?.ToString().ToUpper(),
                                serviceName = serviceName,
                                methodName  = methodName,
                                header      = clientHeader,
                                request     = hasPassword
                                        ? LogUtils.Truncate(LogUtils.MaskPassword(requestObj), MaxLength)
                                        : LogUtils.Truncate(requestObj, MaxLength),
                                response = hasPassword
                                        ? LogUtils.Truncate(LogUtils.MaskPassword(responseObj), MaxLength)
                                        : LogUtils.Truncate(responseObj, MaxLength),
                                requestTime = elapsedTime
                            };

                            logger.Info(typeof(ExtServiceLogs).ToString(), logData.ToString());
                        }
                        catch
                        {
                            // Ignore any exception encountered during logging
                        }
                    }
                        );
                }
            }
            catch
            {
                // Ignore any exception encountered during logging
            }
        }
Exemplo n.º 22
0
        //"{PropertyName} must be unique."
        public IsUniquePropertyValidator(IPropertyValidatorService service, string errorMessage,
                         string action,
                         string controller,
                         HttpVerbs HttpVerb = HttpVerbs.Get,
                         string additionalFields = "")
            : base(errorMessage)
        {
            this._service = service;
            var httpContext = HttpContext.Current;

            if (httpContext != null)
            {
                var httpContextBase = new HttpContextWrapper(httpContext);
                var routeData       = new RouteData();
                var requestContext  = new RequestContext(httpContextBase, routeData);

                var helper       = new UrlHelper(requestContext);
                Url              = helper.Action(action, controller);
                HttpMethod       = HttpVerb.ToString();
                AdditionalFields = additionalFields;
            }
        }
Exemplo n.º 23
0
        public RemoteValidator(string errorMessage, string action, string controller, HttpVerbs httpVerb = HttpVerbs.Get, string additionalFields = "")
            : base(errorMessage)
        {
            var httpContext = HttpContext.Current;

            if (httpContext == null)
            {
                var request = new HttpRequest("/", "http://ubasolutions.com", "");
                var response = new HttpResponse(new StringWriter());
                httpContext = new HttpContext(request, response);
            }

            var httpContextBase = new HttpContextWrapper(httpContext);
            var routeData = new RouteData();
            var requestContext = new RequestContext(httpContextBase, routeData);

            var helper = new UrlHelper(requestContext);

            Url = helper.Action(action, controller);
            HttpMethod = httpVerb.ToString();
            AdditionalFields = additionalFields;
        }
Exemplo n.º 24
0
        public Stream DoDataRequest(string query, HttpVerbs method, Action<Stream> data, string contenttype)
        {
            HttpWebRequest req = WebRequest.Create(new Uri(Url,query)) as HttpWebRequest;

            if (Credentials != null)
                req.Credentials = Credentials;

            req.Method = method.ToString();

            //req.Timeout = System.Threading.Timeout.Infinite;
            if (!string.IsNullOrEmpty(contenttype))
                req.ContentType = contenttype;

            if (data != null)
            {
                using (Stream ps = req.GetRequestStream())
                {
                    data.Invoke(ps);
                }
            }
            try
            {
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

                if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Created)
                    return resp.GetResponseStream();

                throw new RestException(resp.StatusCode, resp.StatusDescription);
            }
            catch (WebException ex)
            {
                HttpWebResponse resp = ex.Response as HttpWebResponse;
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string contents = sr.ReadToEnd();
                throw new RestException(resp.StatusCode, resp.StatusDescription);
            }


        }
        public RequestResult ProcessRequest(string url, HttpVerbs httpVerb, NameValueCollection formValues, NameValueCollection headers)
        {
            if (url == null) throw new ArgumentNullException("url");

            // Fix up URLs that incorrectly start with / or ~/
            if (url.StartsWith("~/"))
                url = url.Substring(2);
            else if(url.StartsWith("/"))
                url = url.Substring(1);

            // Parse out the querystring if provided
            string query = "";
            int querySeparatorIndex = url.IndexOf("?");
            if (querySeparatorIndex >= 0) {
                query = url.Substring(querySeparatorIndex + 1);
                url = url.Substring(0, querySeparatorIndex);
            }                

            // Perform the request
            LastRequestData.Reset();
            var output = new StringWriter();
            string httpVerbName = httpVerb.ToString().ToLower();
            var workerRequest = new SimulatedWorkerRequest(url, query, output, Cookies, httpVerbName, formValues, headers);
            HttpRuntime.ProcessRequest(workerRequest);

            // Capture the output
            AddAnyNewCookiesToCookieCollection();
            Session = LastRequestData.HttpSessionState;
            return new RequestResult
            {
                ResponseText = output.ToString(),
                ActionExecutedContext = LastRequestData.ActionExecutedContext,
                ResultExecutedContext = LastRequestData.ResultExecutedContext,
                Response = LastRequestData.Response,
            };
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="httpVerb">The HTTP verb.</param>
        /// <param name="formValues">The form values.</param>
        /// <param name="headers">The headers.</param>
        /// <returns>The request of executing the simulate request.</returns>
        private RequestResult ProcessRequest(
            string url, HttpVerbs httpVerb, NameValueCollection formValues, NameValueCollection headers)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            // TODO: Doesn't the BCL contain methods to do all this URL handling already?

            // Fix up URLs that incorrectly start with / or ~/
            // TODO: Why is this incorrect? They can be handled fine and make the library easier to use by avoiding unecessary restrictions.
            if (url.StartsWith("~/", true, CultureInfo.InvariantCulture))
            {
                url = url.Substring(2);
            }
            else if (url.StartsWith("/", true, CultureInfo.InvariantCulture))
            {
                url = url.Substring(1);
            }

            // Parse out the querystring if provided
            var query = string.Empty;
            var querySeparatorIndex = url.IndexOf("?");

            if (querySeparatorIndex >= 0)
            {
                query = url.Substring(querySeparatorIndex + 1);
                url = url.Substring(0, querySeparatorIndex);
            }

            // Perform the request
            LastRequestData.Reset();
            var output = new StringWriter();
            var httpVerbName = httpVerb.ToString().ToLower();
            var workerRequest = new SimulatedWorkerRequest(
                url, query, output, this.Cookies, httpVerbName, formValues, headers);
            HttpRuntime.ProcessRequest(workerRequest);

            // Capture the output
            this.AddAnyNewCookiesToCookieCollection();
            this.Session = LastRequestData.HttpSessionState;
            return new RequestResult
                {
                    ResponseText = output.ToString(),
                    ActionExecutedContext = LastRequestData.ActionExecutedContext,
                    ResultExecutedContext = LastRequestData.ResultExecutedContext,
                    Response = LastRequestData.Response,
                };
        }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestHttpRequest" /> class.
 /// </summary>
 /// <param name="url">The URL.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 public TestHttpRequest(string url, HttpVerbs httpMethod = HttpVerbs.Get)
 {
     HttpMethod = httpMethod.ToString();
     Url        = new Uri(url);
     RawUrl     = url;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Specifies the HTTP verb of the request.
 /// </summary>
 /// <param name="verb">The HTTP verb</param>
 public CrudOperationBuilder Type(HttpVerbs verb)
 {
     operation.Type = verb.ToString().ToUpperInvariant();
     return(this);
 }
Exemplo n.º 29
0
 public static RouteData WithMethod(this string url, HttpVerbs verb)
 {
     return(WithMethod(url, verb.ToString("g")));
 }
Exemplo n.º 30
0
        private IDictionary<string, string> StringToSign(HttpVerbs httpMethod, string queryString, IDictionary<string, string> xHeaders, string UTC, IDictionary<string, string> param)
        {
            string stringToSign = String.Concat(httpMethod.ToString().ToUpper(), "\n", UTC, "\n", GetSerializedHeaders(xHeaders), "\n", queryString.Trim());
            {
                string serializedParams = GetSerializedParams(param);
                if (!String.IsNullOrEmpty(serializedParams))
                {
                    stringToSign = String.Concat(stringToSign, "\n", serializedParams);
                }
            }
            string signedData = String.Empty;
            try
            {
                signedData = SignData(stringToSign.ToString());
            }
            catch (Exception e)
            {
                return null;
            }

            string authorizationHeader = String.Concat(AUTHORIZATION_METHOD, AUTHORIZATION_HEADER_FIELD_SEPARATOR, this.appId, AUTHORIZATION_HEADER_FIELD_SEPARATOR, signedData);

            IDictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add(AUTHORIZATION_HEADER_NAME, authorizationHeader);
            headers.Add(DATE_HEADER_NAME, UTC);
            return headers;
        }
Exemplo n.º 31
0
        /// <summary>
        /// Performs an HTTP request to an URL using the specified method and data, returning the response as a string
        /// </summary>
        protected virtual LatchResponse HTTP(Uri URL, HttpVerbs method, IDictionary<string, string> headers, IDictionary<string, string> data)
        {
            HttpWebRequest request = BuildHttpUrlConnection(URL, headers);
            if (request == null)
            {
                throw new HttpException("Request could not be created correctly");
            }
            request.Method = method.ToString();

            try
            {
                if (method.Equals(HttpVerbs.Post) || method.Equals(HttpVerbs.Put))
                {
                    request.ContentType = HTTP_HEADER_CONTENT_TYPE_FORM_URLENCODED;
                    using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
                    {
                        sw.Write(GetSerializedParams(data));
                        sw.Flush();
                    }
                }

                using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
                {
                    string json = sr.ReadToEnd();
                    return new LatchResponse(json);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
Exemplo n.º 32
0
 public bool Contains(HttpVerbs verb)
 {
     return(this.Contains(verb.ToString()));
 }
Exemplo n.º 33
0
        public async Task <T> ExecuteCall <T>(string method, HttpVerbs verb, object bodyParameter = null, IDictionary <string, string> queryStringParameters = null) where T : class
        {
            if (string.IsNullOrEmpty(method))
            {
                throw new ArgumentException($"{nameof(method)} must be set");
            }

            T result = null;

            var uri     = new RestUriBuilder(BaseUrl, method, queryStringParameters);
            var request = GetRequest(uri.ToString(), verb);

            string serializedObject = null;

            if (bodyParameter != null)
            {
                serializedObject = Serializer.Serialize(bodyParameter);

                await RequestWriter.WriteAsync(request, serializedObject);
            }

            string responseString = null;

            try
            {
                var response = (HttpWebResponse)await request.GetResponseAsync();

                using (response)
                {
                    responseString = await ResponseReader.ReadAsync(response);

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        result = Serializer.Deserialize <T>(responseString);
                    }
                }
            }
            catch (WebException we)
            {
                request?.Abort();

                var errorResponse = ((HttpWebResponse)we.Response);

                using (errorResponse)
                {
                    responseString = await ResponseReader.ReadAsync(errorResponse);

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        var errorResult = errorResponse.ContentType.EndsWith("json")
                                        ? Serializer.Deserialize <ErrorResponse>(responseString)
                                        : null;

                        log.Error($"RESTful '{method}' {verb.ToString().ToUpper()} failed with code: '{(int)errorResponse.StatusCode}', message: '{errorResult?.Error ?? errorResult?.Status ?? "NULL"}'", we);
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                request?.Abort();

                log.Error(ex.Message, ex);
                throw;
            }

            return(result);
        }
Exemplo n.º 34
0
 public void Add(HttpVerbs verb)
 {
     this.allowedVerbs.Add(verb.ToString());
 }
Exemplo n.º 35
0
 /// <summary>
 /// Specify the route information for an action.
 /// </summary>
 /// <param name="routeUrl">The url that is associated with this action</param>
 /// <param name="allowedMethods">The httpMethods against which to constrain the route</param>
 public RouteAttribute(string routeUrl, HttpVerbs allowedMethods)
     : this(routeUrl, allowedMethods.ToString().ToUpper().SplitAndTrim(new[] { "," }))
 {
 }
Exemplo n.º 36
0
 /// <summary>
 /// Specify the route information for an action.
 /// </summary>
 /// <param name="routeUrl">The url that is associated with this action</param>
 /// <param name="allowedMethods">The httpMethods against which to constrain the route</param>
 public RouteAttribute(string routeUrl, HttpVerbs allowedMethods)
     : this(routeUrl, allowedMethods.ToString().ToUpper().SplitAndTrim(new[] { "," }))
 {
 }
Exemplo n.º 37
0
        /// <summary>
        /// Executes the rest method.
        /// </summary>
        /// <returns>The rest method.</returns>
        /// <param name="uri">URI.</param>
        /// <param name="verb">Verb.</param>
        /// <param name="userAgent">User agent.</param>
        /// <param name="payload">Payload.</param>
        /// <param name="serializedPayload">Serialized payload.</param>
        /// <param name="parameters">Parameters.</param>
        /// <param name="headers">Headers.</param>
        /// <param name="username">Username.</param>
        /// <param name="password">Password.</param>
        /// <param name="accept">Accept.</param>
        /// <param name="cookieContainer">Cookie container.</param>
        /// <param name="contentType">Content type.</param>
        /// <typeparam name="TSuccess">The 1st type parameter.</typeparam>
        /// <typeparam name="TError">The 2nd type parameter.</typeparam>
        public static RequestResponseSummary <TSuccess, TError> ExecuteRestMethod <TSuccess, TError>(
            Uri uri,
            HttpVerbs verb,
            string userAgent,
            object payload                  = null,
            string serializedPayload        = null,
            List <FormParameter> parameters = null,
            List <Header> headers           = null,
            string username                 = null,
            string password                 = null,
            string accept = null,
            CookieContainer cookieContainer = null,
            string contentType = "application/json"

            )
        {
            string url    = uri.ToString();
            string method = verb.ToString();

            if (payload != null && !string.IsNullOrEmpty(serializedPayload) && parameters != null)
            {
                throw new ArgumentOutOfRangeException("payload, serializedPayload, and pameters are mutually exclusive.");
            }

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            var summary = new RequestResponseSummary <TSuccess, TError>();

            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

                ManageHeaders(
                    httpWebRequest: httpWebRequest,
                    method: method,
                    headers: headers,
                    username: username,
                    password: password,
                    accept: accept,
                    contentType: contentType,
                    userAgent: userAgent,
                    cookieContainer: cookieContainer
                    );

                BuildPayload(payload, serializedPayload, parameters, httpWebRequest, ref summary);

                SubmitResponseUsing <TSuccess, TError>(ref summary, httpWebRequest);

                return(summary);
            }
            catch (WebException ex)
            {
                HandleWebException <TSuccess, TError>(
                    summary: ref summary,
                    url: url,
                    ex: ex);
                return(summary);
            }
            catch (Exception ex)
            {
                summary.Results        = default(TSuccess);
                summary.UnhandledError = ex.Message;
                summary.Status         = 0;
                return(summary);
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Submits the multipart form.
        /// </summary>
        /// <returns>The multipart form.</returns>
        /// <param name="uri">URI.</param>
        /// <param name="verb">Verb.</param>
        /// <param name="userAgent">User agent.</param>
        /// <param name="encoding">Encoding.</param>
        /// <param name="uploadFile">Upload file.</param>
        /// <param name="headers">Headers.</param>
        /// <param name="parameters">Parameters.</param>
        /// <param name="username">Username.</param>
        /// <param name="password">Password.</param>
        /// <param name="accept">Accept.</param>
        /// <param name="contentType">Content type.</param>
        /// <param name="cookieContainer">Cookie container.</param>
        /// <typeparam name="TSuccess">The 1st type parameter.</typeparam>
        /// <typeparam name="TError">The 2nd type parameter.</typeparam>
        public static RequestResponseSummary <TSuccess, TError> SubmitMultipartForm <TSuccess, TError>(
            Uri uri,
            HttpVerbs verb,
            string userAgent,
            Encoding encoding               = null,
            string uploadFile               = null,
            List <Header> headers           = null,
            List <FormParameter> parameters = null,
            string username    = null,
            string password    = null,
            string accept      = null,
            string contentType = "multipart/form-data",
            CookieContainer cookieContainer = null
            )
        {
            var method  = verb.ToString();
            var summary = new RequestResponseSummary <TSuccess, TError>();

            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }

                var httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
                if (httpWebRequest == null)
                {
                    throw new NullReferenceException("request is not a http request");
                }

                string formDataBoundary = "--" + DateTime.Now.ToString("ssfff");
                contentType = string.Format("{0}; boundary={1}", contentType, formDataBoundary);

                ManageHeaders(
                    httpWebRequest: httpWebRequest,
                    method: method,
                    headers: headers,
                    username: username,
                    password: password,
                    accept: accept,
                    contentType: contentType,
                    userAgent: userAgent,
                    cookieContainer: cookieContainer
                    );

                BuildMultiPartPayload(
                    encoding: encoding,
                    parameters: parameters,
                    contentType: contentType,
                    request: httpWebRequest,
                    formDataBoundary: formDataBoundary);

                SubmitRequestDispose <TSuccess, TError>(
                    summary: ref summary,
                    httpWebRequest: httpWebRequest);


                return(summary);
            }
            catch (WebException ex)
            {
                HandleWebException <TSuccess, TError>(
                    summary: ref summary,
                    url: uri.ToString(),
                    ex: ex);
                return(summary);
            }
            catch (Exception ex)
            {
                summary.SerializedResponse = ex.Message;
                summary.Status             = 0;
                summary.UnhandledError     = ex.Message;
                return(summary);
            }
        }