Example #1
0
        public void GetPublicFacingUrlSSLForwarder2()
        {
            HttpRequest req             = new HttpRequest("a.aspx", "http://someinternalhost/a.aspx?a=b", "a=b");
            var         serverVariables = new NameValueCollection();

            serverVariables["HTTP_X_FORWARDED_PROTO"] = "https";
            serverVariables["HTTP_HOST"] = "somehost:999";
            Uri actual   = new HttpRequestWrapper(req).GetPublicFacingUrl(serverVariables);
            Uri expected = new Uri("https://somehost:999/a.aspx?a=b");

            Assert.AreEqual(expected, actual);
        }
Example #2
0
        public IRestResponse PostAssignmentProvider(AssignmentProvider provider)
        {
            var accept_request = new HttpRequestWrapper(_baseUrlAssignmentApi, _useLocalProxy, _bearerToken)
                                 .SetMethod(Method.POST)
                                 .SetResourse($"/providers")
                                 .AddJsonContent(new List <AssignmentProvider>()
            {
                provider
            });

            return(accept_request.Execute());
        }
        private async Task LoadItems()
        {
            lasyLoader.IsVisible = true;
            await Task.Delay(1000);

            try
            {
                HttpRequestWrapper wrapper = new HttpRequestWrapper();
                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                parameters.Add(new KeyValuePair <string, string>("company_code", Constant.CompanyID));
                //   parameters.Add(new KeyValuePair<string, string>("city_id", AppData.UserCityId));
                //  parameters.Add(new KeyValuePair<string, string>("breaking_news", "1"));
                parameters.Add(new KeyValuePair <string, string>("page", (Items.data.current_page + 1).ToString()));
                var jsonstr = await wrapper.GetResponseAsync(Constant.APIs[(int)Constant.APIName.NewsList], parameters);

                if (jsonstr.ToString() == "NoInternet")
                {
                    lstView.IsVisible       = false;
                    MainContainer.IsVisible = false;
                    NoInternet.IsVisible    = true;
                }
                else
                {
                    BreakingNewsModel NewItems = new BreakingNewsModel();
                    NewItems = JsonConvert.DeserializeObject <BreakingNewsModel>(jsonstr);

                    List <News_List_Bnews> asd = new List <News_List_Bnews>();
                    asd = Items.data.news_list.ToList();

                    foreach (News_List_Bnews list in NewItems.data.news_list)
                    {
                        asd.Add(list);
                    }

                    Items.data.news_list = asd.ToArray();

                    Items.data.current_page = NewItems.data.current_page;
                    lstView.ItemsSource     = Items.data.news_list;
                    lstView.HeightRequest   = Items.data.news_list.Count() * lstView.RowHeight;

                    lstView.IsVisible       = true;
                    MainContainer.IsVisible = true;
                }
            }
            catch (Exception ex)
            {
            }

            lasyLoader.IsVisible    = false;
            lstView.IsVisible       = true;
            MainContainer.IsVisible = true;
        }
Example #4
0
        protected override HttpResponseWrapper Request(HttpRequestWrapper req)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var request = WebRequest.Create(req.Url);

            request.Method = req.Method;
            foreach (var header in req.Headers)
            {
                if (!WebHeaderCollection.IsRestricted(header.Key))
                {
                    request.Headers.Add(header.Key, header.Value);
                }
                else
                {
                    if (header.Key == "Range")
                    {
                        var one = header.Value.Split('=');
                        var two = one[1].Split('-');
                        (request as HttpWebRequest).AddRange(one[0],
                                                             int.Parse(two[0]), int.Parse(two[1]));
                    }
                    else
                    {
                        throw new Exception("Restricted header");
                    }
                }
            }
            var resp   = request.GetResponseNoException();
            var length = (int)resp.ContentLength;
            var body   = new byte[0];

            if (length > 0)
            {
                var dataStream = resp.GetResponseStream();
                var reader     = new BinaryReader(dataStream);
                body = reader.ReadBytes(length);
                reader.Close();
            }
            resp.Close();
            var headers = new Dictionary <string, string>();

            foreach (var header in resp.Headers.AllKeys)
            {
                headers.Add(header, resp.Headers[header]);
            }
            return(new HttpResponseWrapper()
            {
                Status = (byte)resp.StatusCode,
                Headers = headers,
                Body = new List <byte>(body)
            });
        }
        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            HttpRequest   request = Context.Request;
            StringBuilder msg     = new StringBuilder()
                                    .Append(Environment.NewLine)
                                    .Append(DateTime.Now.ToShortDateString())
                                    .Append("UserAgent:   ").Append(request.UserAgent).Append(Environment.NewLine)
                                    .Append("AbsoluteUri: ").Append(request.Url.AbsoluteUri).Append(Environment.NewLine)
                                    .Append("UrlReferrer:   ").Append(request.UrlReferrer).Append(Environment.NewLine)
                                    .Append("Exception:   ").Append(Server.GetLastError()).Append(Environment.NewLine)
                                    .Append("-------------------------------------------------------------------------------").Append(Environment.NewLine);
            //Logger.Default.Error(msg.ToString());


            bool iserrorview = true;

            if (iserrorview) //是否开启错误视图
            {
                var lastError = Server.GetLastError();
                if (lastError != null)
                {
                    var httpError = lastError as HttpException;
                    if (httpError != null)
                    {
                        //400与404错误不记录日志,并都以自定义404页面响应
                        var httpCode = httpError.GetHttpCode();
                        if (httpCode == 400 || httpCode == 404)
                        {
                            Response.StatusCode = 404;
                            Server.ClearError();
                            Response.Redirect("/Error_404.html", true);
                            return;
                        }
                    }
                    //对于路径错误不记录日志,并都以自定义404页面响应
                    if (lastError.TargetSite.ReflectedType == typeof(System.IO.Path))
                    {
                        Response.StatusCode = 404;
                        Server.ClearError();
                        Response.Redirect("/Error_404.html");
                        return;
                    }
                    Response.StatusCode = 500;
                    Server.ClearError();
                    var httprequestwrapper = new HttpRequestWrapper(request);
                    if (!httprequestwrapper.IsAjaxRequest())
                    {
                        Response.Redirect("/Error_500.html", true);
                    }
                }
            }
        }
        public void GivenIDeleteABookWith()
        {
            var bookDel = ScenarioContext.Current.Get <Book>("Book");

            var request = new HttpRequestWrapper()
                          .SetMethod(Method.DELETE)
                          .SetResource("api/books").AddParameter("id", bookDel.Id);

            _restResponse = request.Execute();

            ScenarioContext.Current.Remove("srvResponse");
            ScenarioContext.Current.Add("srvResponse", _restResponse);
        }
        public void WhenISearchForABookWith(string param, string searchTerm)
        {
            var request = new HttpRequestWrapper()
                          .SetMethod(Method.GET)
                          .SetResource("api/books?").AddParameter($"{param}=", searchTerm);

            _restResponse = request.Execute();

            if (_restResponse.Content.Length > 0)
            {
                ScenarioContext.Current.Add("NotEmpty", _restResponse.Content);
            }
        }
        public void WhenITryToAccessTheBookBy(string p0)
        {
            var bookToAcc = ScenarioContext.Current.Get <Book>("Book");

            var request = new HttpRequestWrapper()
                          .SetMethod(Method.GET)
                          .SetResource("api/books").AddParameter("id", bookToAcc.Id);

            _restResponse = request.Execute();

            ScenarioContext.Current.Remove("srvResponse");
            ScenarioContext.Current.Add("srvResponse", _restResponse);
        }
        public void GivenAVoterId(long id)
        {
            var request = new HttpRequestWrapper()
                          .SetMethod(Method.GET)
                          .SetResourse("/elections/GetVoter")
                          .AddParameter("id", id);

            _restResponse = new RestResponse();
            _restResponse = request.Execute();

            _statusCode = _restResponse.StatusCode;
            _voter      = JsonConvert.DeserializeObject <Voters>(_restResponse.Content);
        }
        public void WhenTheLoginRequestSend()
        {
            var request = new HttpRequestWrapper()
                          .SetMethod(Method.POST)
                          .SetResourse("/Login")
                          .AddParameterWithoutObject(user)
            ;

            _restResponse = new RestResponse();
            _restResponse = request.Execute();
            _statusCode   = _restResponse.StatusCode;
            userResponse  = JsonConvert.DeserializeObject <LoginUserDto>(_restResponse.Content);
        }
Example #11
0
        public void WhenTheStudentOfThatIdGetAndRequestToDeleteRecordMade()
        {
            Dictionary <string, string> header = new Dictionary <string, string>();

            header.Add("Authorization", "bearer " + _Token);
            var Request = new HttpRequestWrapper()
                          .SetMethod(Method.DELETE)
                          .AddHeaders(header)
                          .SetResourse("/api/Student/?id=" + _id);

            _restResponse = new RestResponse();
            _restResponse = Request.Execute();
        }
Example #12
0
 public GlobalHttpContext()
 {
     useContext = Current;
     response   = new HttpResponseWrapper(useContext);
     request    = new HttpRequestWrapper(useContext);
     try {
         if (useContext.Session != null)
         {
             session = new HttpSessionState(useContext);
         }
     } catch { }
     server = new HttpServerUtility();
 }
Example #13
0
        public void WhenIUpdateAnExistingProperty(string newAddress, decimal newPrice)
        {
            _property.Address = newAddress;
            _property.Price   = newPrice;

            var request = new HttpRequestWrapper()
                          .SetMethod(Method.PUT)
                          .SetResourse("/api/properties/")
                          .AddJsonContent(_property);

            //_restResponse = new RestResponse();
            var response = request.Execute();
        }
        private void Context_BeginRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            var request = new HttpRequestWrapper(context.Request);

            if (!request.IsAjaxRequest())
            {
                // currently we only care about ajax requests since full page loads will go through the normal CMS pipeline
                return;
            }

            GigyaAccountHelper.ProcessRequestChecks(context);
        }
Example #15
0
        private async void Validate_Tapped(object sender, EventArgs e)
        {
            Loader.IsVisible = true;

            // await Task.Delay(500);

            if (ChkNullAll() == true)
            {
                HttpRequestWrapper wrapper = new HttpRequestWrapper();
                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                parameters.Add(new KeyValuePair <string, string>("company_code", Constant.CompanyID));
                parameters.Add(new KeyValuePair <string, string>("phone_no", Mobileno.Text.Trim()));
                parameters.Add(new KeyValuePair <string, string>("password", Password.Text.Trim()));
                parameters.Add(new KeyValuePair <string, string>("device_type", Constant.DeviceType));
                parameters.Add(new KeyValuePair <string, string>("device_token", AppData.DeviceToken));
                parameters.Add(new KeyValuePair <string, string>("app_version", Constant.AppVersion));

                string jsonstr = await wrapper.GetResponseAsync(Constant.APIs[(int)Constant.APIName.MerchantLoginCheck], parameters);

                if (jsonstr.ToString() == "NoInternet")
                {
                    NoInternet.IsVisible = true;
                    MainFrame.IsVisible  = false;
                }
                else
                {
                    try
                    {
                        result = JsonConvert.DeserializeObject <MerchantLoginModel>(jsonstr);
                    }
                    catch
                    {
                        await DisplayAlert("Internal server error", "Please try again later", "Cancel");
                    }
                    if (result.responseText == "Success")
                    {
                        AppData.MerchantUserName = result.data.user_data.name;
                        AppData.MerchantUserId   = result.data.user_data.user_id;
                        AppData.IsMerchantLogin  = true;
                        await Navigation.PushModalAsync(new MerchantVerification());
                    }
                    else
                    {
                        await DisplayAlert("Error", "Phone Number/Password does not match please register first ", "OK");

                        await Navigation.PopModalAsync();
                    }
                }
            }
            Loader.IsVisible = false;
        }
Example #16
0
        public override void Execute(System.Web.HttpContext context)
        {
            IHttpRequest  request  = new HttpRequestWrapper(ServicePath, OperationName, context.Request);
            IHttpResponse response = new HttpResponseWrapper(context.Response);

            HostContext.InitRequest(request, response);

            if (!EndpointHost.MetadataMap[request.ServicePath].MetadataFeatureEnabled)
            {
                new NotFoundHttpHandler(request.ServicePath).ProcessRequest(request, response, request.OperationName);
                return;
            }
            ProcessRequest(request, response, OperationName);
        }
Example #17
0
        public void WhenTheRequestToEditRecordMade()
        {
            Dictionary <string, string> header = new Dictionary <string, string>();

            header.Add("Authorization", "bearer " + _Token);
            var Request = new HttpRequestWrapper()
                          .SetMethod(Method.PUT)
                          .AddHeaders(header)
                          .SetResourse("/api/Student")
                          .AddJsonContent(model);

            _restResponse = new RestResponse();
            _restResponse = Request.Execute();
        }
Example #18
0
        private async void CheckUniqueKey(object sender, EventArgs e)
        {
            if (UniqueCode.Text == null)
            {
                await DisplayAlert("Failure", "Please Enter Booking ID", "OK");
            }
            else
            {
                Loader.IsVisible = true;;
                HttpRequestWrapper wrapper = new HttpRequestWrapper();
                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                parameters.Add(new KeyValuePair <string, string>("company_code", Constant.CompanyID));
                parameters.Add(new KeyValuePair <string, string>("merchant_id", AppData.MerchantUserId));
                parameters.Add(new KeyValuePair <string, string>("booking_id", UniqueCode.Text));

                string jsonstr = await wrapper.GetResponseAsync(Constant.APIs[(int)Constant.APIName.MerchantCodeVerification], parameters);

                if (jsonstr.ToString() == "NoInternet")
                {
                    NoInternet.IsVisible = true;
                    MainFrame.IsVisible  = false;
                }
                else
                {
                    try
                    {
                        object  dec = JsonConvert.DeserializeObject(jsonstr); // deserializing Json string (it will deserialize Json string)
                        JObject obj = JObject.Parse(dec.ToString());          // it will parse deserialize Json object
                        if (obj["responseText"].ToString() == "Success")
                        {
                            await DisplayAlert("Success", "It is a Valid Ticket", "OK");

                            //JObject obj2 = JObject.Parse(obj["data"].ToString());  // now after parsing deserialize Json object you can get individual values by key i.e.
                            //var x = obj2["payurl"].ToString();
                            //await Navigation.PushAsync(new PaymentGatewayNav(x));
                        }

                        else
                        {
                            await DisplayAlert("Failure", "It is not a Valid Ticket", "OK");
                        }
                    }
                    catch
                    {
                        await DisplayAlert("Internal server error", "Please try again later", "Cancel");
                    }
                }
                Loader.IsVisible = false;
            }
        }
Example #19
0
        protected async void LoadItems(string NextPage)
        {
            //MainFrame.IsVisible = false;
            lasyLoader.IsVisible = true;
            await Task.Delay(1000);

            try
            {
                //if (Items.data == null)
                //{
                ShowsModel         NewItems = new ShowsModel();
                HttpRequestWrapper wrapper  = new HttpRequestWrapper();
                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                parameters.Add(new KeyValuePair <string, string>("company_code", Constant.CompanyID));
                parameters.Add(new KeyValuePair <string, string>("playlistId", PlaylistId));
                parameters.Add(new KeyValuePair <string, string>("pageToken", NextPage));
                var jsonstr = await wrapper.GetResponseAsync(Constant.APIs[(int)Constant.APIName.ShowsPlaylistVideos], parameters);

                if (jsonstr.ToString() == "NoInternet")
                {
                    lstView.IsVisible    = false;
                    MainFrame.IsVisible  = false;
                    NoInternet.IsVisible = true;
                }
                else
                {
                    NewItems = JsonConvert.DeserializeObject <ShowsModel>(jsonstr);
                }

                List <VideoItem> asd = new List <VideoItem>();
                asd = Items.data.playlists.items.ToList();

                foreach (VideoItem list in NewItems.data.playlists.items)
                {
                    asd.Add(list);
                }

                Items.data.playlists.items         = asd.ToArray();
                Items.data.playlists.nextPageToken = NewItems.data.playlists.nextPageToken;
                lstView.ItemsSource = Items.data.playlists.items;


                //}
            }
            catch (Exception ex)
            {
            }

            lasyLoader.IsVisible = true;
        }
Example #20
0
        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;
            var request     = new HttpRequestWrapper(application.Request);
            var headers     = request.Headers;
            var authValue   = headers["Authorization"];

            if (string.IsNullOrEmpty(authValue))
            {
                return;
            }

            var scheme      = authValue.Substring(0, authValue.IndexOf(' '));
            var parameter   = authValue.Substring(scheme.Length).Trim();
            var credentials = ParseAuthorizationHeader(parameter);

            if (credentials == null)
            {
                return;
            }

            var user     = credentials.Username;
            var password = credentials.Password;

            #region Verificacion Credenciales

            var existeUsuario = ApiKeyBasicUsuarios.UsuariosAutorizados.Any(ele => ele.Key == user && ele.Value == password);

            if (!existeUsuario)
            {
                return;
            }

            #region Add Principal Roles

            //var roles = new List<string>
            //{
            //    "admin",
            //    "regente",
            //    "af"
            //};
            //var principal = new GenericPrincipal(new GenericIdentity(user), roles.ToArray());

            #endregion

            var principal = new GenericPrincipal(new GenericIdentity(user), null);
            PutPrincipal(principal);

            #endregion
        }
Example #21
0
        private void CheckForAuthFailure(object sender, EventArgs e)
        {
            var app      = sender as HttpApplication;
            var response = new HttpResponseWrapper(app.Response);
            var request  = new HttpRequestWrapper(app.Request);
            var context  = new HttpContextWrapper(app.Context);

            if (true.Equals(context.Items["RequestWasNotAuthorized"]) &&
                request.IsAjaxRequest())
            {
                response.StatusCode = 401;
                response.ClearContent();
            }
        }
Example #22
0
        private static void OnBeginRequest(object sender, EventArgs e)
        {
            _lastRequestDateTime = DateTime.UtcNow;

            var httpContext = ((HttpApplication)sender).Context;
            var httpRequest = new HttpRequestWrapper(httpContext.Request);

            // HACK: If it's a Razor extension, add a dummy extension to prevent WebPages for blocking it,
            // as we need to serve those files via /vfs
            // Yes, this is an abuse of the trace module
            if (httpRequest.FilePath.IndexOf("vfs/", StringComparison.OrdinalIgnoreCase) >= 0 &&
                (httpRequest.FilePath.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase) ||
                 httpRequest.FilePath.EndsWith(".vbhtml", StringComparison.OrdinalIgnoreCase)))
            {
                httpContext.Server.TransferRequest(httpRequest.FilePath + Constants.DummyRazorExtension, preserveForm: true);
                return;
            }

            // Always trace the startup request.
            ITracer tracer = TraceStartup(httpContext);

            // Skip certain paths
            if (TraceExtensions.ShouldSkipRequest(httpRequest))
            {
                TraceServices.RemoveRequestTracer(httpContext);
                return;
            }

            tracer = tracer ?? TraceServices.CreateRequestTracer(httpContext);

            if (tracer == null || tracer.TraceLevel <= TraceLevel.Off)
            {
                return;
            }

            var attribs = GetTraceAttributes(httpContext);

            AddTraceLevel(httpContext, attribs);

            foreach (string key in httpContext.Request.Headers)
            {
                if (!key.Equals("Authorization", StringComparison.OrdinalIgnoreCase) &&
                    !key.Equals("X-MS-CLIENT-PRINCIPAL-NAME", StringComparison.OrdinalIgnoreCase))
                {
                    attribs[key] = httpContext.Request.Headers[key];
                }
            }

            httpContext.Items[_stepKey] = tracer.Step("Incoming Request", attribs);
        }
Example #23
0
        /// <summary>
        /// Autor: Enderson Namias
        /// Fecha: 11-11-2019
        /// Descripción: Metodo que permite consultar la cotizacion de los Reales
        /// </summary>
        /// <param name="academic">Parametros filtros para la busqueda de informacion</param>
        /// <returns>Clase con la información encontrada</returns>
        public HashSet <format> SearchReal()
        {
            var Request = new HttpRequestWrapper(HttpContext.Current.Request);
            var headers = HeaderExtensions.CopyHeadersFrom(Request);

            _invoke = new commons.invoker(headers);
            var invokeSelect      = (ResultCambioModel)_invoke.get("/v1/quotes/BRL/ARS/json", typeof(ResultCambioModel));
            HashSet <format> data = new HashSet <format>();

            data.Add(new format {
                precio = Convert.ToDecimal(invokeSelect.result.value), moneda = "Dolar"
            });
            return(data);
        }
        public virtual FormatedList <T> DataTables()
        {
            IQueryable <T> queryable;
            var            dbQuery = ctx.Set <T>();

            queryable = dbQuery.AsQueryable();

            var request   = HttpContext.Current.Request;
            var wrapper   = new HttpRequestWrapper(request);
            var parser    = new DataTablesParser <T>(wrapper, queryable);
            var datatable = parser.Parse();

            return(datatable);
        }
        private async void loadListdata(string Type)
        {
            try
            {
                HttpRequestWrapper wrapper = new HttpRequestWrapper();
                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                parameters.Add(new KeyValuePair <string, string>("company_code", Constant.CompanyID));
                parameters.Add(new KeyValuePair <string, string>("type", Type));
                parameters.Add(new KeyValuePair <string, string>("user_id", AppData.UserId));
                var jsonstr = await wrapper.GetResponseAsync(Constant.APIs[(int)Constant.APIName.PollContestQuestionList], parameters);

                if (jsonstr.ToString() == "NoInternet")
                {
                    NoInternet.IsVisible = true;
                    MainFrame.IsVisible  = false;
                    NoDataPage.IsVisible = false;
                }
                else
                {
                    try
                    {
                        Items = JsonConvert.DeserializeObject <PollContestList>(jsonstr);
                    }
                    catch
                    {
                        NoInternet.IsVisible = false;
                        MainFrame.IsVisible  = false;
                        NoDataPage.IsVisible = true;
                    }
                    if (Items.data.poll_list.Count() <= 0)
                    {
                        NoDataPage.IsVisible = true;
                        MainFrame.IsVisible  = false;
                    }
                    MainFrame.IsVisible   = true;
                    lstView.ItemsSource   = Items.data.poll_list;
                    lstView.HeightRequest = (Items.data.poll_list.Count() * lstView.RowHeight) + 5;
                }
            }
            catch (Exception ex)
            {
            }


            Loader.IsVisible = false;
            lstView.IsPullToRefreshEnabled = true;
            lstView.RefreshCommand         = PullToRefreshCommand;
            lstView.IsRefreshing           = IsRefreshing;
            lstView.SetBinding(ListView.IsRefreshingProperty, "IsRefreshing");
        }
Example #26
0
        protected void Application_Error(Object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            if (exception.InnerException != null)
            {
                exception = exception.InnerException;
            }

            var httpRequestBase = new HttpRequestWrapper(Request);

            Log.Error(exception, httpRequestBase);
            Server.ClearError();
        }
        public void GivenIMakeACallToTheAPIWithNewGameData()
        {
            _hostUrl            = @"http://localhost:52201/addgame/winner=" + ScenarioContext.Current["winningPlayer"].ToString() + "/loser=" + ScenarioContext.Current["losingPlayer"].ToString();
            _httpRequestWrapper = new HttpRequestWrapper();
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Content-Type", "application/json");
            var response = _httpRequestWrapper.
                           SetMethod(Method.POST).
                           AddHeaders(headers).
                           Execute(_hostUrl);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
Example #28
0
        private static string GetPayload(HttpRequestMessage request)
        {
            var requestContext            = request.Properties["MS_RequestContext"];
            HttpRequestWrapper webRequest = requestContext.GetType().GetProperty("WebRequest").GetValue(requestContext) as HttpRequestWrapper;

            if (webRequest == null)
            {
                return(String.Empty);
            }

            byte[] buffer = new byte[webRequest.ContentLength];
            webRequest.InputStream.Read(buffer, 0, webRequest.ContentLength);
            return(System.Text.Encoding.Default.GetString(buffer));
        }
        void AuthenticateScheduler(object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;
            var request     = new HttpRequestWrapper(application.Request);

            // スケジューラからのリクエストか検証
            if (!request.Headers.AllKeys.Contains("x-ms-scheduler-jobid"))
            {
                return;
            }

            // スケジューラからのリクエストの場合は、シークレットキーを認識してRoleを付与
            AuthenticateUsingSharedSecret(request);
        }
Example #30
0
 protected void Application_EndRequest()
 {
     if (Context.Response.StatusCode == 404)
     {
         bool isAjax = new HttpRequestWrapper(Context.Request).IsAjaxRequest();
         if (isAjax || Context.Request.Path.ToLower().IndexOf("/api") > -1)
         {
             Response.Write(Context.Request.RawUrl);
         }
         else
         {
             Response.RedirectToRoute("Default", new { controller = "Error", action = "Error404", errorUrl = Context.Request.RawUrl });
         }
     }
 }
Example #31
0
        public Account CreateCustomer(Customer customer)
        {
            //username & password will be both retrieved by login process
            _restSharpComponent.TokenizeRequest(new User() { username="******",
                                                             password ="******",
                                                             grant_type ="password"
                                                            });
            _wrapper = new HttpRequestWrapper(_restSharpComponent, "http://localhost:51313/api/customers", Method.POST);

            var serializedRequest = JsonConvert.SerializeObject(customer);

            _wrapper.Post(serializedRequest);

            var account = _wrapper.Execute<Account>();
            return account;
        }
        public override void Execute(HttpContext context)
        {
            var httpReq = new HttpRequestWrapper(context.Request);
            var httpRes = new HttpResponseWrapper(context.Response);
            var operationName = httpReq.QueryString["op"];
            if (!EndpointHost.Metadata.IsVisible(httpReq, Format, operationName))
            {
                EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Service Not Available");
                return;
            }

            var writer = new HtmlTextWriter(context.Response.Output);
            context.Response.ContentType = "text/html";

            ProcessOperations(writer, new HttpRequestWrapper(GetType().Name, context.Request));
        }
        // Entry point for ASP.NET
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated;
            var httpReq = new HttpRequestWrapper(pathTranslated, context.Request);
            foreach (var rawHttpHandler in RawHttpHandlers)
            {
                var reqInfo = rawHttpHandler(httpReq);
                if (reqInfo != null) return reqInfo;
            }

            var mode = _endpointHost.Config.ServiceStackHandlerFactoryPath;
            var pathInfo = context.Request.GetPathInfo();

            //WebDev Server auto requests '/default.aspx' so recorrect path to different default document
            if (mode == null && (url == "/default.aspx" || url == "/Default.aspx"))
                pathInfo = "/";

            //Default Request /
            if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
            {
                //Exception calling context.Request.Url on Apache+mod_mono
                var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl();
                if (ApplicationBaseUrl == null)
                    SetApplicationBaseUrl(absoluteUrl);

                //e.g. CatchAllHandler to Process Markdown files
                var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
                if (catchAllHandler != null) return catchAllHandler;

                return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler;
            }

            if (mode != null && pathInfo.EndsWith(mode))
            {
                var requestPath = context.Request.Path.ToLower();
                if (requestPath == "/" + mode
                    || requestPath == mode
                    || requestPath == mode + "/")
                {
                    if (context.Request.PhysicalPath != WebHostPhysicalPath
                        || !File.Exists(Path.Combine(context.Request.PhysicalPath, DefaultRootFileName ?? "")))
                    {
                        return new IndexPageHttpHandler();
                    }
                }

                var okToServe = ShouldAllow(context.Request.FilePath);
                return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler;
            }

            return GetHandlerForPathInfo(
                context.Request.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated)
                   ?? NotFoundHttpHandler;
        }
 internal static string GetRedirectUrl(string redirectUrl)
 {
     var request = new HttpRequestWrapper(HttpContext.Current.Request);
     return GetRedirectUrl(request, redirectUrl, VirtualPathUtility.ToAppRelative);
 }
        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            var httpReq = new HttpRequestWrapper("NotFoundHttpHandler", request);
            if (!request.IsLocal)
            {
                ProcessRequest(httpReq, new HttpResponseWrapper(response), null);
                return;
            }

            Log.ErrorFormat("{0} Request not found: {1}", request.UserHostAddress, request.RawUrl);

            var sb = new StringBuilder();
            sb.AppendLine("Handler for Request not found: \n\n");

            sb.AppendLine("Request.ApplicationPath: " + request.ApplicationPath);
            sb.AppendLine("Request.CurrentExecutionFilePath: " + request.CurrentExecutionFilePath);
            sb.AppendLine("Request.FilePath: " + request.FilePath);
            sb.AppendLine("Request.HttpMethod: " + request.HttpMethod);
            sb.AppendLine("Request.MapPath('~'): " + request.MapPath("~"));
            sb.AppendLine("Request.Path: " + request.Path);
            sb.AppendLine("Request.PathInfo: " + request.PathInfo);
            sb.AppendLine("Request.ResolvedPathInfo: " + httpReq.PathInfo);
            sb.AppendLine("Request.PhysicalPath: " + request.PhysicalPath);
            sb.AppendLine("Request.PhysicalApplicationPath: " + request.PhysicalApplicationPath);
            sb.AppendLine("Request.QueryString: " + request.QueryString);
            sb.AppendLine("Request.RawUrl: " + request.RawUrl);
            try
            {
                sb.AppendLine("Request.Url.AbsoluteUri: " + request.Url.AbsoluteUri);
                sb.AppendLine("Request.Url.AbsolutePath: " + request.Url.AbsolutePath);
                sb.AppendLine("Request.Url.Fragment: " + request.Url.Fragment);
                sb.AppendLine("Request.Url.Host: " + request.Url.Host);
                sb.AppendLine("Request.Url.LocalPath: " + request.Url.LocalPath);
                sb.AppendLine("Request.Url.Port: " + request.Url.Port);
                sb.AppendLine("Request.Url.Query: " + request.Url.Query);
                sb.AppendLine("Request.Url.Scheme: " + request.Url.Scheme);
                sb.AppendLine("Request.Url.Segments: " + request.Url.Segments);
            }
            catch (Exception ex)
            {
                sb.AppendLine("Request.Url ERROR: " + ex.Message);
            }
            if (IsIntegratedPipeline.HasValue)
                sb.AppendLine("App.IsIntegratedPipeline: " + IsIntegratedPipeline);
            if (!WebHostPhysicalPath.IsNullOrEmpty())
                sb.AppendLine("App.WebHostPhysicalPath: " + WebHostPhysicalPath);
            if (!WebHostRootFileNames.IsEmpty())
                sb.AppendLine("App.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
            if (!ApplicationBaseUrl.IsNullOrEmpty())
                sb.AppendLine("App.ApplicationBaseUrl: " + ApplicationBaseUrl);
            if (!DefaultRootFileName.IsNullOrEmpty())
                sb.AppendLine("App.DefaultRootFileName: " + DefaultRootFileName);
            if (!DefaultHandler.IsNullOrEmpty())
                sb.AppendLine("App.DefaultHandler: " + DefaultHandler);
            if (!ServiceStackHttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
                sb.AppendLine("App.DebugLastHandlerArgs: " + ServiceStackHttpHandlerFactory.DebugLastHandlerArgs);

            response.ContentType = "text/plain";
            response.StatusCode = 404;
            response.EndHttpRequest(skipClose:true, afterBody: r => r.Write(sb.ToString()));
        }
Example #36
0
 public static WebImage GetImageFromRequest(string postedFileName = null) {
     var request = new HttpRequestWrapper(HttpContext.Current.Request);
     return GetImageFromRequest(request, postedFileName);
 }
        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            var httpReq = new HttpRequestWrapper("NotFoundHttpHandler", request);

            var sb = new StringBuilder();
            sb.AppendLine("Handler for Request not found: \n\n");

            sb.AppendLine("Request.ApplicationPath: " + request.ApplicationPath);
            sb.AppendLine("Request.CurrentExecutionFilePath: " + request.CurrentExecutionFilePath);
            sb.AppendLine("Request.FilePath: " + request.FilePath);
            sb.AppendLine("Request.HttpMethod: " + request.HttpMethod);
            sb.AppendLine("Request.MapPath('~'): " + request.MapPath("~"));
            sb.AppendLine("Request.Path: " + request.Path);
            sb.AppendLine("Request.PathInfo: " + request.PathInfo);
            sb.AppendLine("Request.ResolvedPathInfo: " + httpReq.PathInfo);
            sb.AppendLine("Request.PhysicalPath: " + request.PhysicalPath);
            sb.AppendLine("Request.PhysicalApplicationPath: " + request.PhysicalApplicationPath);
            sb.AppendLine("Request.QueryString: " + request.QueryString);
            sb.AppendLine("Request.RawUrl: " + request.RawUrl);
            try
            {
                sb.AppendLine("Request.Url.AbsoluteUri: " + request.Url.AbsoluteUri);
                sb.AppendLine("Request.Url.AbsolutePath: " + request.Url.AbsolutePath);
                sb.AppendLine("Request.Url.Fragment: " + request.Url.Fragment);
                sb.AppendLine("Request.Url.Host: " + request.Url.Host);
                sb.AppendLine("Request.Url.LocalPath: " + request.Url.LocalPath);
                sb.AppendLine("Request.Url.Port: " + request.Url.Port);
                sb.AppendLine("Request.Url.Query: " + request.Url.Query);
                sb.AppendLine("Request.Url.Scheme: " + request.Url.Scheme);
                sb.AppendLine("Request.Url.Segments: " + request.Url.Segments);
            }
            catch (Exception ex)
            {
                sb.AppendLine("Request.Url ERROR: " + ex.Message);
            }
            if (IsIntegratedPipeline.HasValue)
                sb.AppendLine("App.IsIntegratedPipeline: " + IsIntegratedPipeline);
            if (!WebHostPhysicalPath.IsNullOrEmpty())
                sb.AppendLine("App.WebHostPhysicalPath: " + WebHostPhysicalPath);
            if (!WebHostRootFileNames.IsEmpty())
                sb.AppendLine("App.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
            if (!ApplicationBaseUrl.IsNullOrEmpty())
                sb.AppendLine("App.ApplicationBaseUrl: " + ApplicationBaseUrl);
            if (!DefaultRootFileName.IsNullOrEmpty())
                sb.AppendLine("App.DefaultRootFileName: " + DefaultRootFileName);
            if (!DefaultHandler.IsNullOrEmpty())
                sb.AppendLine("App.DefaultHandler: " + DefaultHandler);
            if (!ServiceStackHttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
                sb.AppendLine("App.DebugLastHandlerArgs: " + ServiceStackHttpHandlerFactory.DebugLastHandlerArgs);

            response.ContentType = "text/plain";
            response.StatusCode = 404;
            response.Write(sb.ToString());

            //Apache+mod_mono doesn't like this
            //response.OutputStream.Flush();
            //response.Close();
        }
Example #38
0
        public void WhenIRequestToViewAllLoans()
        {
            var resourceServer = ConfigurationManager.AppSettings["ResourceServer"];

            _wrapper = new HttpRequestWrapper(_restSharpComponent, string.Format("{0}api/loans", resourceServer), Method.GET);

            _loans = _wrapper.Execute<List<Loan>>();
        }