Пример #1
1
 /// <summary>
 /// Gets the request.
 /// </summary>
 /// <param name="url">The URL.</param>
 /// <param name="requestParamDic">The request parameter dic.</param>
 /// <returns></returns>
 public Dictionary<string, string> postRequest(string url, Dictionary<string, string> requestParamDic)
 {
     httpPost = new HttpPost(new Uri(url));
     foreach (KeyValuePair<string, string> entry in requestParamDic)
     {
         httpPost.Parameters.Add(entry.Key, entry.Value);
     }
     //Get the response
     response = client.Execute(httpPost);
     //Get the response string
     string responseString = EntityUtils.ToString(response.Entity);
     //Get the Response Code and Save it
     string responseCode = response.ResponseCode.ToString();
     //Parse the response and return the values in the Dictionary
     Dictionary<String, String> responseCollection = null;
     if (responseCode == "200" && response != null)
     {
         //Console.WriteLine("Received the response" + responseString);
         responseCollection = new Dictionary<string, string>();
     }
     else
     {
         //Console.WriteLine("No Result returned");
     }
     return responseCollection;
 }
    public void login(HttpRequest request, HttpResponse response, System.Web.SessionState.HttpSessionState session)
    {
        if(String.IsNullOrEmpty(serviceLogoutUrl))
            throw new Exception("ERROR: service Logout Url not defined");
        if(String.IsNullOrEmpty(centralizedSPUrl))
            throw new Exception("ERROR: centralized SP Url not defined");

        if(String.IsNullOrEmpty(request.Params["xmlAttrib"])){
            string serviceUrl = request.RawUrl;

            string auth = "<auth><serviceURL>"+serviceUrl+"</serviceURL><logoutURL>"+serviceLogoutUrl+"</logoutURL>";
            if(!String.IsNullOrEmpty(authenticationMethodList)){
                auth += "<authnContextList>";
                foreach(string authenticationMethod in authenticationMethodList)
                    auth += "<authnContext>"+authenticationMethod+"</authnContext>";
                auth += "</authnContextList>";
            }
            auth += "</auth>";

            string authB64 = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(auth));

            response.Redirect(centralizedSPUrl+"/PoA?xmlAuth="+System.Web.HttpUtility.UrlEncode(authB64));
        } else {
            string userAttributes = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(request.Params["xmlAttrib"]));

            session["userAttributes"] = userAttributes;

            if(!String.IsNullOrEmpty(request.Params["ReturnUrl"]))
                response.Redirect(request.Params["ReturnUrl"]);
        }
    }
Пример #3
0
 public static void pageHome(ref UberCMS.Misc.PageElements pageElements, HttpRequest request, HttpResponse response, ref StringBuilder content)
 {
     content.Append(
         templates[TEMPLATES_KEY]["home"]
         );
     pageElements["TITLE"] = "Welcome!";
 }
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="Cronofy.CronofyResponseException"/> class.
        /// </summary>
        /// <param name="message">
        /// A message that describes the error.
        /// </param>
        /// <param name="response">
        /// The response that caused the exception, must not be null.
        /// </param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if <paramref name="response"/> is null.
        /// </exception>
        public CronofyResponseException(string message, HttpResponse response)
            : base(message)
        {
            Preconditions.NotNull("response", response);

            this.response = response;
        }
 private void GenerateImage(
     HttpResponse response,
     string textToInsert,
     int width,
     int height,
     Color backgroundColor,
     FontFamily fontFamily,
     float emSize,
     Brush brush,
     float x,
     float y,
     string contentType,
     ImageFormat imageFormat)
 {
     using (Bitmap bitmap = new Bitmap(width, height))
     {
         using (Graphics graphics = Graphics.FromImage(bitmap))
         {
             graphics.Clear(backgroundColor);
             graphics.DrawString(textToInsert, new Font(fontFamily, emSize), brush, x, y);
             response.ContentType = contentType;
             bitmap.Save(response.OutputStream, imageFormat);
         }
     }
 }
 public virtual void Uninitialize()
 {
     _features = default(FeatureReferences<FeatureInterfaces>);
     if (_request != null)
     {
         UninitializeHttpRequest(_request);
         _request = null;
     }
     if (_response != null)
     {
         UninitializeHttpResponse(_response);
         _response = null;
     }
     if (_authenticationManager != null)
     {
         UninitializeAuthenticationManager(_authenticationManager);
         _authenticationManager = null;
     }
     if (_connection != null)
     {
         UninitializeConnectionInfo(_connection);
         _connection = null;
     }
     if (_websockets != null)
     {
         UninitializeWebSocketManager(_websockets);
         _websockets = null;
     }
 }
Пример #7
0
		async public Task RouteAsync(HttpRequest Request, HttpResponse Response)
		{
			Console.WriteLine("Request: {0}", Request.Url);
			//var UrlParts = Request.Url.Split(new[] { '?' }, 2);
			//var 
			var Path = Request.Url.Path;

			foreach (var Route in Routes)
			{
				if (Route.Key.IsMatch(Path))
				{
					await Route.Value(Request, Response);
					return;
				}
			}
			if (DefaultRoute == null)
			{
				Response.Headers["Content-Type"] = "text/html";
				Console.WriteLine("No rute found for '" + Path + "'");
				throw (new Exception("No route found!"));
			}
			else
			{
				await DefaultRoute(Request, Response);
			}
		}
Пример #8
0
        /// <inheritdoc />
        protected override Task WriteFileAsync(HttpResponse response)
        {
            var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>();
            bufferingFeature?.DisableResponseBuffering();

            return response.Body.WriteAsync(FileContents, offset: 0, count: FileContents.Length);
        }
Пример #9
0
        public StaticFileContext(HttpContext context, StaticFileOptions options, PathString matchUrl)
        {
            _context = context;
            _options = options;
            _matchUrl = matchUrl;
            _request = context.Request;
            _response = context.Response;

            _method = null;
            _isGet = false;
            _isHead = false;
            _subPath = PathString.Empty;
            _contentType = null;
            _fileInfo = null;
            _length = 0;
            _lastModified = new DateTime();
            _etag = null;
            _etagQuoted = null;
            _lastModifiedString = null;
            _ifMatchState = PreconditionState.Unspecified;
            _ifNoneMatchState = PreconditionState.Unspecified;
            _ifModifiedSinceState = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;
            _ranges = null;
        }
Пример #10
0
    void WriteResponseForPostJson(HttpRequest request, HttpResponse response)
    {
        // read request JSON
        uint requestedCount = ReadCount(request.Body);

        // write response JSON
        var json = new JsonWriter<ResponseFormatter>(response.Body, prettyPrint: false);
        json.WriteObjectStart();
        json.WriteArrayStart();
        for (int i = 0; i < requestedCount; i++) {
            json.WriteString("hello!"); 
        }
        json.WriteArrayEnd();
        json.WriteObjectEnd();

        // write headers
        var headers = response.Headers;
        headers.AppendHttpStatusLine(HttpVersion.V1_1, 200, new Utf8String("OK"));
        headers.Append("Content-Length : ");
        headers.Append(response.Body.CommitedBytes);
        headers.AppendHttpNewLine();
        headers.Append("Content-Type : text/plain; charset=UTF-8");
        headers.AppendHttpNewLine();
        headers.Append("Server : .NET Core Sample Server");
        headers.AppendHttpNewLine();
        headers.Append("Date : ");
        headers.Append(DateTime.UtcNow, 'R');
        headers.AppendHttpNewLine();
        headers.AppendHttpNewLine();
    }
Пример #11
0
 public static void SignOut(HttpResponse Response, HttpRequest Request)
 {
     HttpCookie cookie = Request.Cookies["DareSessionID"];
     int id = int.Parse(cookie.Value);
     SessionManager.RemoveSession(id);
     if (Response.Cookies.AllKeys.Contains("DareSessionID")) Response.Cookies.Remove("DareSessionID");
 }
        public static HttpResponse ToHttpCall(this WebRequest request)
        {
            var reset = new ManualResetEvent(false);
            IAsyncResult result = null;

            var thread = new Thread(() =>
            {
                result = request.BeginGetResponse(r => { }, null);
                reset.Set();
            });
            thread.Start();
            thread.Join();
            reset.WaitOne();

            try
            {
                var response = request.EndGetResponse(result).As<HttpWebResponse>();
                return new HttpResponse(response);
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    throw;
                }

                var errorResponse = new HttpResponse(e.Response.As<HttpWebResponse>());

                return errorResponse;
            }
        }
 public BaseAppelRequstHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, string VersionHeader)
 {
     this.Request = Request;
     this.Response = Response;
     this.Prefix = Prefix;
     this.VersionHeader = VersionHeader;
 }
 public CompetitionResultAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate CompetitionResultsTemplate, UriTemplate ResultResourceTemplate, string AcceptHeader)
     : base(Request, Response, Prefix, AcceptHeader)
 {
     this.CompetitionResultsTemplate = CompetitionResultsTemplate;
     this.ResultResourceTemplate = ResultResourceTemplate;
     processRequest();
 }
Пример #15
0
        public HttpResponse Login()
        {
            var userRepo = UserRepositoryLocator.Instance;
            HttpResponse response = null;

            var authentication = Context.Request.Headers["Authorization"];
            //se não existir header, realizar basic authentication
            if(authentication == null)
            {
                response = new HttpResponse(HttpStatusCode.Unauthorized, new TextContent("Not Authorized"))
                                .WithHeader("WWW-Authenticate", "Basic realm=\"Private Area\"");
            }else
            {
                authentication = authentication.Replace("Basic ", "");

                string userPassDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(authentication));
                string[] userPasswd = userPassDecoded.Split(':');
                string username = userPasswd[0];
                string passwd = userPasswd[1];

                User user = null;
                if (userRepo.TryAuthenticate(username, passwd, out user))
                {
                    response = new HttpResponse(HttpStatusCode.Found).WithHeader("Location", "/")
                                    .WithCookie(new Cookie(COOKIE_AUTH_NAME, user.Identity.Name, "/"));
                }
            }

            return response;
        }
Пример #16
0
 public void Handle(HttpRequest req, HttpResponse resp, JsonRpcHandler jsonRpcHandler)
 {
     if(req.HttpMethod != "POST")
     {
         resp.Status = "405 Method Not Allowed";
         return;
     }
     if(!req.ContentType.StartsWith("application/json"))
     {
         resp.Status = "415 Unsupported Media Type";
         return;
     }
     JToken json;
     try
     {
         json = JToken.ReadFrom(new JsonTextReader(req.Content));
     }
     catch(Exception e)
     {
         resp.Status = "400 Bad Request";
         resp.ContentType = "text/plain";
         resp.Content.WriteLine(e);
         return;
     }
     resp.Status = "200 OK";
     resp.ContentType = "application/json";
     using(var jsonWriter = new JsonTextWriter(resp.Content))
     {
         new JsonSerializer().Serialize(jsonWriter, jsonRpcHandler.Handle(json));
     }
 }
Пример #17
0
 public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullUrl, long _speed)
 {
     try
     {
         FileStream myFile = new FileStream(_fullUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         BinaryReader br = new BinaryReader(myFile);
         try
         {
             _Response.AddHeader("Accept-Ranges", "bytes");
             _Response.Buffer = false;
             long fileLength = myFile.Length;
             long startBytes = 0;
             int pack = 10240; //10K bytes
             int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
             if (_Request.Headers["Range"] != null)
             {
                 _Response.StatusCode = 206;
                 string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                 startBytes = Convert.ToInt64(range[1]);
             }
             _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
             if (startBytes != 0)
             {
                 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
             }
             _Response.AddHeader("Connection", "Keep-Alive");
             _Response.ContentType = "application/octet-stream";
             _Response.AddHeader("Content-Disposition", "attachment;filename="
                                 + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
             br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
             int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
             for (int i = 0; i < maxCount; i++)
             {
                 if (_Response.IsClientConnected)
                 {
                     _Response.BinaryWrite(br.ReadBytes(pack));
                     Thread.Sleep(sleep);
                 }
                 else
                 {
                     i = maxCount;
                 }
             }
         }
         catch
         {
             return false;
         }
         finally
         {
             br.Close();
             myFile.Close();
         }
     }
     catch
     {
         return false;
     }
     return true;
 }
Пример #18
0
    public ExchangeHTTP(HttpResponse response, string flag)
    {
        this.encoding = response.Output.Encoding;
        this.responseStream = response.Filter;

        this.flag = flag;
    }
 public static void SetLanguage(string Language, HttpResponse Response)
 {
     HttpCookie cookie = new HttpCookie("DareLang");
     cookie.Value = Language;
     cookie.Expires = DateTime.Now.AddYears(7);
     Response.Cookies.Add(cookie);
 }
Пример #20
0
        public static HttpResponse FromString(string value)
        {
            var result = new HttpResponse();
            result.Line = HttpStatusLine.FromString(result.Load(value));

            return result;
        }
Пример #21
0
        public MockHttpTransaction(IHttpRequest request)
        {
            if (request == null)
               throw new ArgumentNullException ("request");

            Request = request;
            Response = new HttpResponse (this, Encoding.Default);
        }
 protected override void beforeEach()
 {
     theResponse = endpoints.GetByInput(new TargetModel(), acceptType: "application/json", configure: r =>
     {
         r.AllowAutoRedirect = false;
         r.Headers.Add(AjaxExtensions.XRequestedWithHeader, AjaxExtensions.XmlHttpRequestValue);
     });
 }
Пример #23
0
        public HttpContext(HttpRequest request, HttpResponse response)
        {
            if (request == null) throw new ArgumentNullException(nameof(request));
            if (response == null) throw new ArgumentNullException(nameof(response));

            Request = request;
            Response = response;
        }
Пример #24
0
		/// <summary>
		/// Initializes a new instance of <see cref="HttpContext"/> class.
		/// </summary>
		internal HttpContext(HttpListenerContext context)
		{
			var listenerContext = context;

			Request = new HttpRequest(listenerContext.Request);

			Response = new HttpResponse(listenerContext.Response);
		}
 public DefaultHttpContext(IFeatureCollection features)
 {
     _features = features;
     _request = new DefaultHttpRequest(this, features);
     _response = new DefaultHttpResponse(this, features);
     _connection = new DefaultConnectionInfo(features);
     _authenticationManager = new DefaultAuthenticationManager(features);
 }
 public FencerAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate FencerRootTemplate, UriTemplate FencerResourceTemplate, UriTemplate FencerResultTemplate, string AcceptHeader)
     : base(Request, Response, Prefix, AcceptHeader)
 {
     this.FencerRootTemplate = FencerRootTemplate;
     this.FencerResourceTemplate = FencerResourceTemplate;
     this.FencerResultTemplate = FencerResultTemplate;
     processRequest();
 }
Пример #27
0
 private static async Task DumpConfig(HttpResponse response, IConfiguration config, string indentation = "")
 {
     foreach (var child in config.GetSubKeys())
     {
         await response.WriteAsync(indentation + "[" + child.Key + "] " + config.Get(child.Key) + "\r\n");
         await DumpConfig(response, child.Value, indentation + "  ");
     }
 }
Пример #28
0
 /// <summary>
 /// Creates and sends an HttpResponse packet for an exception, wraps it to an error 401
 /// </summary>
 private void Send412(HttpResponse response)
 {
     response.Status = "412";
     response.Write("<html><head><title>412 Precondition Failed</title></head><body>");
     response.Write("<h3>Precondition Failed (412)</h3>");
     response.Write("Unable to find a necessary cookie, please ensure that your browser supports cookies and have them enabled.");
     response.Write("</body></html>");
 }
 public NetCoreResponse(NetCoreRequest request, HttpResponse response)
 {
     this.request = request;
     this.response = response;
     this.Items = new Dictionary<string, object>();
     this.Cookies = new NetCoreCookies(response);
     response.StatusCode = 200;
 }
Пример #30
0
        public IndexMissingException(string index, HttpRequest request, HttpResponse response)
            : base(request, response)
        {
            if (string.IsNullOrWhiteSpace(index))
                throw new ArgumentNullException("index", "IndexMissingException requires the index name.");

            Index = index;
        }
Пример #31
0
 internal JQueryDataTablesHandler(SqlCommand cmd, string draw, int start, int length, HttpResponse response) : base(cmd, response)
 {
     this.draw   = draw;
     this.start  = start;
     this.length = length;
 }
        public T GetAcsResponse <T>(AcsRequest <T> request, bool autoRetry, int maxRetryNumber) where T : AcsResponse
        {
            HttpResponse httpResponse = this.DoAction(request, autoRetry, maxRetryNumber);

            return(ParseAcsResponse(request, httpResponse));
        }
        public T GetAcsResponse <T>(AcsRequest <T> request, string regionId, Credential credential) where T : AcsResponse
        {
            HttpResponse httpResponse = this.DoAction(request, regionId, credential);

            return(ParseAcsResponse(request, httpResponse));
        }
Пример #34
0
 private void RespondWithRedirect(HttpResponse response, string pathBase)
 {
     response.Redirect(pathBase + "/" + _toPath);
 }
Пример #35
0
 public static void AddApplicationError(this HttpResponse response, string message)
 {
     response.Headers.Add("Application-Error", message);
     // CORS
     response.Headers.Add("access-control-expose-headers", "Application-Error");
 }
        /* goodG2B() - use goodsource and badsink */
        public static void GoodG2BSink(Dictionary <int, string> dataDictionary, HttpRequest req, HttpResponse resp)
        {
            string data = dataDictionary[2];
            String osCommand;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                /* running on Windows */
                osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir ";
            }
            else
            {
                /* running on non-Windows */
                osCommand = "/bin/ls ";
            }
            /* POTENTIAL FLAW: command injection */
            Process process = Process.Start(osCommand + data);

            process.WaitForExit();
        }
Пример #37
0
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            while (true)
            {
                data = ""; /* Initialize data */
                /* Read data using an outbound tcp connection */
                {
                    try
                    {
                        /* Read data using an outbound tcp connection */
                        using (TcpClient tcpConn = new TcpClient("host.example.org", 39544))
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using an outbound tcp connection */
                                data = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
                break;
            }
            while (true)
            {
                if (data != null)
                {
                    string[] names        = data.Split('-');
                    int      successCount = 0;
                    try
                    {
                        /* FIX: Use prepared statement and concatenate CommandText (properly) */
                        using (SqlConnection dbConnection = IO.GetDBConnection())
                        {
                            dbConnection.Open();
                            using (SqlCommand goodSqlCommand = new SqlCommand(null, dbConnection))
                            {
                                for (int i = 0; i < names.Length; i++)
                                {
                                    SqlParameter nameParam = new SqlParameter("@name", SqlDbType.VarChar, 100);
                                    nameParam.Value             = names[i];
                                    goodSqlCommand.CommandText += "update users set hitcount=hitcount+1 where name=@name;";
                                }
                                goodSqlCommand.Prepare();
                                int affectedRows = goodSqlCommand.ExecuteNonQuery();
                                successCount += affectedRows;
                                IO.WriteLine("Succeeded in " + successCount + " out of " + names.Length + " queries.");
                            }
                        }
                    }
                    catch (SqlException exceptSql)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, "Error getting database connection", exceptSql);
                    }
                }
                break;
            }
        }
Пример #38
0
 public override void Good(HttpRequest req, HttpResponse resp)
 {
     GoodG2B(req, resp);
     GoodB2G(req, resp);
 }
Пример #39
0
 public static void AddAppError(this HttpResponse response, string message)
 {
     response.Headers.Add("App-Error", message);
     response.Headers.Add("Access-Control-Expose-Headers", "App-Error");
     response.Headers.Add("Access-Control-Allow-Origin", "*");
 }
        static async void WriteResponse(HttpRequest currentReqest, string url, HttpResponseMessage responseMessage, HttpResponse response, bool isAjax)
        {
            var result = await responseMessage.Content.ReadAsStringAsync();

            var ReportServer = url.Contains("/ReportServer/") ? "ReportServer" : "Reports";

            var reportUri = new Uri(url);
            var proxyUrl  = String.Format("{0}://{1}{2}/ssrsproxy/{3}/{4}/{5}", currentReqest.Scheme, currentReqest.Host.Value, currentReqest.PathBase,
                                          reportUri.Scheme, reportUri.Host, reportUri.Port);

            if (isAjax && result.IndexOf("|") != -1)
            {
                var builder = new StringBuilder();

                var delimiterIndex = 0;
                var length         = 0;
                var index          = 0;

                var type    = "";
                var id      = "";
                var content = "";

                while (index < result.Length)
                {
                    delimiterIndex = result.IndexOf("|", index);
                    if (delimiterIndex == -1)
                    {
                        break;
                    }
                    length = int.Parse(result.Substring(index, delimiterIndex - index));
                    if ((length % 1) != 0)
                    {
                        break;
                    }
                    index          = delimiterIndex + 1;
                    delimiterIndex = result.IndexOf("|", index);
                    if (delimiterIndex == -1)
                    {
                        break;
                    }
                    type           = result.Substring(index, delimiterIndex - index);
                    index          = delimiterIndex + 1;
                    delimiterIndex = result.IndexOf("|", index);
                    if (delimiterIndex == -1)
                    {
                        break;
                    }
                    id    = result.Substring(index, delimiterIndex - index);
                    index = delimiterIndex + 1;
                    if ((index + length) >= result.Length)
                    {
                        break;
                    }
                    content = result.Substring(index, length);
                    index  += length;
                    if (result.Substring(index, 1) != "|")
                    {
                        break;
                    }
                    index++;

                    content = content.Replace($"/{ReportServer}/", $"{proxyUrl}/{ReportServer}/", StringComparison.InvariantCultureIgnoreCase);
                    if (content.Contains("./ReportViewer.aspx"))
                    {
                        content = content.Replace("./ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase);
                    }
                    else
                    {
                        content = content.Replace("ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase);
                    }

                    builder.Append(String.Format("{0}|{1}|{2}|{3}|", content.Length, type, id, content));
                }

                result = builder.ToString();
            }
            else
            {
                result = result.Replace($"/{ReportServer}/", $"{proxyUrl}/{ReportServer}/", StringComparison.InvariantCultureIgnoreCase);

                if (result.Contains("./ReportViewer.aspx"))
                {
                    result = result.Replace("./ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase);
                }
                else
                {
                    result = result.Replace("ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase);
                }
            }

            response.Headers.Remove("Content-Length");
            response.Headers.Add("Content-Length", new string[] { System.Text.Encoding.UTF8.GetByteCount(result).ToString() });

            await response.WriteAsync(result);
        }
Пример #41
0
 public void init(HttpRequest res, HttpResponse rep)
 {
     request  = res;
     response = rep;
     readQueryString();
 }
Пример #42
0
 internal JQueryDataTablesHandler(SqlCommand cmd, string draw, int start, int length, HttpResponse response)
     : base(cmd, draw, start, length, response)
 {
 }
 /* goodB2G() - use badsource and goodsink */
 public static void GoodB2GSink(string data , HttpRequest req, HttpResponse resp)
 {
     CWE89_SQL_Injection__Web_Database_ExecuteScalar_53d.GoodB2GSink(data , req, resp);
 }
Пример #44
0
    public void ProcessRequest(HttpContext context)
    {
#if SINGLE_THREADED
        lock (_lock)
        {
#endif

        Context  = context;
        Request  = context.Request;
        Response = context.Response;

        Response.ContentType = "text/plain";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        try
        {
            string method = Request.Form["m"];

            if (method == null)
            {
                method = Request.QueryString["m"];
            }

            if (method == null)
            {
                method = "DefaultMethod";
            }

            // some service ASHX files in the GPV point to parent handler classes, so find the requested method
            // on the parent class of the current ASHX class via reflection if not found on the current class

            Type handlerType = this.GetType();

            BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod;

            MemberInfo[] memberInfo = handlerType.GetMember(method, MemberTypes.Method, bindingFlags);

            if (memberInfo.Length == 0)
            {
                handlerType = handlerType.BaseType;
                memberInfo  = handlerType.GetMember(method, MemberTypes.Method, bindingFlags);
            }

            if (memberInfo.Length > 0 && memberInfo[0].GetCustomAttributes(false).FirstOrDefault(o => o is WebServiceMethodAttribute) != null)
            {
                handlerType.InvokeMember(method, bindingFlags, null, this, null);
            }
            else
            {
                throw new Exception(String.Format("Invalid method specified: {0}", method));
            }
        }
        catch (Exception ex)
        {
            if (!(ex is System.Threading.ThreadAbortException))
            {
                if (Debugger.IsAttached)
                {
                    throw ex.InnerException != null ? ex.InnerException : ex;
                }

                else
                {
                    Response.StatusCode = 500;

                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }

                    if (ex is AppException)
                    {
                        Response.AddHeader("GPV-Error", ex.Message);
                    }
                }
            }
        }
#if SINGLE_THREADED
    }
#endif
    }
Пример #45
0
        /// <summary>
        /// 接口提供程序,在收到请求后,调用此方法,并提供业务逻辑处理的委托方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key">安全 Key</param>
        /// <param name="allowTimespanSeconds">时间戳允许相差的秒数,一般为 30 秒</param>
        /// <param name="HandleRequest">委托回调的方法,用于应用程序处理业务逻辑,返回接口应返回的字符串</param>
        /// <param name="errorDescription">如果有错误发生,此为错误描述</param>
        /// <returns></returns>
        public static int Handle(HttpContext context, string key, int allowTimespanSeconds, DelegateHandleRequest HandleRequest, ref string errorDescription)
        {
            errorDescription = "";

            #region 参数及安全性校验

            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("在使用 Shove.Gateways.GeneralRestGateway.Handle 方法解析参数并处理业务时,必须提供一个用于摘要签名用的 key (俗称 MD5 加盐)。");
            }

            HttpRequest  req = null;
            HttpResponse res = null;

            if (context == null)
            {
                errorDescription = "Http 上下文错误。";

                return(-1);
            }

            req = context.Request;
            res = context.Response;

            if ((req == null) || (res == null))
            {
                errorDescription = "Http 上下文错误。";

                return(-2);
            }

            string[] keys = new string[req.Query.Keys.Count];
            req.Query.Keys.CopyTo(keys, 0);

            if ((keys == null) || (keys.Length == 0))
            {
                errorDescription = "没有找到 Query 参数,接口数据非法。";

                return(-3);
            }

            Dictionary <string, object> parameters = new Dictionary <string, object>();
            string _s = "", _t = "";

            for (int i = 0; i < req.Query.Count; i++)
            {
                if (keys[i] == "_s")
                {
                    _s = req.Query["_s"];

                    continue;
                }
                else if (keys[i] == "_t")
                {
                    _t = HttpUtility.UrlDecode(req.Query["_t"], Encoding.UTF8);
                }

                parameters.Add(keys[i], HttpUtility.UrlDecode(req.Query[keys[i]], Encoding.UTF8));
            }

            if (string.IsNullOrEmpty(_s) || string.IsNullOrEmpty(_t))
            {
                errorDescription = "缺少 _s 或 _t 参数,接口数据非法。";

                return(-4);
            }

            string[] ParameterNames = new string[parameters.Count];
            parameters.Keys.CopyTo(ParameterNames, 0);
            Array.Sort(ParameterNames);

            string signData = "";

            for (int i = 0; i < parameters.Count; i++)
            {
                signData += (ParameterNames[i] + "=" + parameters[ParameterNames[i]].ToString() + ((i < parameters.Count - 1) ? "&" : ""));
            }

            DateTime timestamp = Convert.StrToDateTime(_t, DateTime.Now.AddYears(-30).ToString("yyyy-MM-dd HH:mm:ss"));
            TimeSpan ts = DateTime.Now - timestamp;

            if ((allowTimespanSeconds > 0) && (Math.Abs(ts.TotalSeconds) > allowTimespanSeconds))
            {
                errorDescription = "访问超时。";

                return(-5);
            }

            if (string.Compare(Security.Encrypt.MD5(signData + key, Encoding.UTF8), _s, true) != 0)
            {
                errorDescription = "签名错误,接口数据非法。";

                return(-6);
            }

            parameters.Remove("_t");

            #endregion

            #region 委托应用程序处理接口参数,参数不包括 _s, _t 等安全变量

            string result = "";

            try
            {
                result = HandleRequest(parameters, ref errorDescription);
            }
            catch (Exception e)
            {
                errorDescription = "应用程序的代理回调程序遇到异常,详细原因是:" + e.Message;

                return(-7);
            }

            if (!string.IsNullOrEmpty(result))
            {
                res.WriteAsync(result);
            }

            #endregion

            //[shove]
            //res.End();

            return(0);
        }
Пример #46
0
 public Task get_greetings(HttpResponse response)
 {
     response.ContentType = "text/plain";
     return(response.WriteAsync("Greetings and salutations!"));
 }
Пример #47
0
 /// <summary>
 /// Gets strongly typed HTTP response headers.
 /// </summary>
 /// <param name="response">The <see cref="HttpResponse"/>.</param>
 /// <returns>The <see cref="ResponseHeaders"/>.</returns>
 public static ResponseHeaders GetTypedHeaders(this HttpResponse response)
 {
     return(new ResponseHeaders(response.Headers));
 }
Пример #48
0
 private static void WriteStat <T>(HttpResponse response, string name, T value)
 {
     Write(response, name + ": " + value.ToString());
 }
 /* goodB2G() - use badsource and goodsink */
 public static void GoodB2GSink(string data, HttpRequest req, HttpResponse resp)
 {
     CWE89_SQL_Injection__Web_QueryString_Web_ExecuteScalar_54c.GoodB2GSink(data, req, resp);
 }
Пример #50
0
        public override void Bad(HttpRequest req, HttpResponse resp)
        {
            string data;

            data = ""; /* Initialize data */
            /* Read data using a listening tcp connection */
            {
                TcpListener listener = null;
                try
                {
                    listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                    listener.Start();
                    using (TcpClient tcpConn = listener.AcceptTcpClient())
                    {
                        /* read input from socket */
                        using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                        {
                            /* POTENTIAL FLAW: Read data using a listening tcp connection */
                            data = sr.ReadLine();
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
                finally
                {
                    if (listener != null)
                    {
                        try
                        {
                            listener.Stop();
                        }
                        catch (SocketException se)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                        }
                    }
                }
            }
            if (data != null)
            {
                string[]   names         = data.Split('-');
                int        successCount  = 0;
                SqlCommand badSqlCommand = null;
                try
                {
                    using (SqlConnection dbConnection = IO.GetDBConnection())
                    {
                        badSqlCommand.Connection = dbConnection;
                        dbConnection.Open();
                        for (int i = 0; i < names.Length; i++)
                        {
                            /* POTENTIAL FLAW: data concatenated into SQL statement used in CommandText, which could result in SQL Injection */
                            badSqlCommand.CommandText += "update users set hitcount=hitcount+1 where name='" + names[i] + "';";
                        }
                        var affectedRows = badSqlCommand.ExecuteNonQuery();
                        successCount += affectedRows;
                        IO.WriteLine("Succeeded in " + successCount + " out of " + names.Length + " queries.");
                    }
                }
                catch (SqlException exceptSql)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, "Error getting database connection", exceptSql);
                }
                finally
                {
                    try
                    {
                        if (badSqlCommand != null)
                        {
                            badSqlCommand.Dispose();
                        }
                    }
                    catch (SqlException exceptSql)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, "Error disposing SqlCommand", exceptSql);
                    }
                }
            }
        }
Пример #51
0
        protected void ExportAsImage(Image image, string fileName, ImageFormat imageFormat, HttpResponse response)
        {
            if (ControllerContext == null)
            {
                throw new ArgumentNullException("Context");
            }
            string disposition = "content-disposition";

            response.AddHeader(disposition, "attachment; filename=" + fileName);
            if (imageFormat != ImageFormat.Emf)
            {
                image.Save(Response.OutputStream, imageFormat);
            }
            Response.End();
        }
Пример #52
0
 public EmailTestService(HttpRequest request, HttpResponse response)
 {
     Request  = request;
     Response = response;
 }
Пример #53
0
        private static async Task ValidateMethodWithScenarioAsync(
            MethodDefinition method,
            ScenarioDefinition scenario,
            IServiceAccount primaryAccount,
            IServiceAccount secondaryAccount,
            ValidationResults results,
            ValidationOptions options = null)
        {
            if (null == method)
            {
                throw new ArgumentNullException("method");
            }
            if (null == scenario)
            {
                throw new ArgumentNullException("scenario");
            }
            if (null == primaryAccount)
            {
                throw new ArgumentNullException("primaryAccount");
            }
            if (null == results)
            {
                throw new ArgumentNullException("results");
            }

            var actionName = scenario.Description;

            // Check to see if the account + scenario scopes are aligned

            string[] requiredScopes = method.RequiredScopes.Union(scenario.RequiredScopes).ToArray();

            if (!primaryAccount.Scopes.ProvidesScopes(requiredScopes, options.IgnoreRequiredScopes))
            {
                var missingScopes = from scope in requiredScopes where !primaryAccount.Scopes.Contains(scope) select scope;

                results.AddResult(actionName,
                                  new ValidationWarning(ValidationErrorCode.RequiredScopesMissing,
                                                        null,
                                                        "Scenario was not run. Scopes required were not available: {0}", missingScopes.ComponentsJoinedByString(",")));
                return;
            }

            string[] requiredApiVersions = method.RequiredApiVersions.Union(scenario.RequiredApiVersions).ToArray();

            if (!primaryAccount.ApiVersions.ProvidesApiVersions(requiredApiVersions))
            {
                var missingApiVersions = from apiVersion in requiredApiVersions where !primaryAccount.ApiVersions.Contains(apiVersion) select apiVersion;

                results.AddResult(actionName,
                                  new ValidationWarning(ValidationErrorCode.RequiredApiVersionsMissing,
                                                        null,
                                                        "Scenario was not run. Api Versions required were not available: {0}", missingApiVersions.ComponentsJoinedByString(",")));
                return;
            }

            string[] requiredTags = method.RequiredTags.Union(scenario.RequiredTags).ToArray();

            if (!primaryAccount.Tags.ProvidesTags(requiredTags))
            {
                var missingTags = from tag in requiredTags where !primaryAccount.Tags.Contains(tag) select tag;

                results.AddResult(actionName,
                                  new ValidationWarning(ValidationErrorCode.RequiredTagsMissing,
                                                        null,
                                                        "Scenario was not run. Tags required were not available: {0}", missingTags.ComponentsJoinedByString(",")));
                return;
            }

            // Generate the tested request by "previewing" the request and executing
            // all test-setup procedures
            long startTicks           = DateTimeOffset.UtcNow.Ticks;
            var  requestPreviewResult = await method.GenerateMethodRequestAsync(scenario, method.SourceFile.Parent, primaryAccount, secondaryAccount);

            TimeSpan generateMethodDuration = new TimeSpan(DateTimeOffset.UtcNow.Ticks - startTicks);

            // Check to see if an error occured building the request, and abort if so.
            var generatorResults = results[actionName /*+ " [test-setup requests]"*/];

            generatorResults.AddResults(requestPreviewResult.Messages, requestPreviewResult.IsWarningOrError ? ValidationOutcome.Error :  ValidationOutcome.Passed);
            generatorResults.Duration = generateMethodDuration;

            if (requestPreviewResult.IsWarningOrError)
            {
                return;
            }

            // We've done all the test-setup work, now we have the real request to make to the service
            HttpRequest requestPreview = requestPreviewResult.Value;

            results.AddResult(
                actionName,
                new ValidationMessage(null, "Generated Method HTTP Request:\r\n{0}", requestPreview.FullHttpText()));

            HttpParser   parser           = new HttpParser();
            HttpResponse expectedResponse = null;

            if (!string.IsNullOrEmpty(method.ExpectedResponse))
            {
                expectedResponse = parser.ParseHttpResponse(method.ExpectedResponse);
            }

            // Execute the actual tested method (the result of the method preview call, which made the test-setup requests)
            startTicks = DateTimeOffset.UtcNow.Ticks;
            var issues         = new IssueLogger();
            var actualResponse = await requestPreview.GetResponseAsync(primaryAccount, issues);

            TimeSpan actualMethodDuration = new TimeSpan(DateTimeOffset.UtcNow.Ticks - startTicks);

            var requestResults = results[actionName];

            if (actualResponse.RetryCount > 0)
            {
                requestResults.AddResults(
                    new ValidationError[]
                    { new ValidationWarning(ValidationErrorCode.RequestWasRetried, null, "HTTP request was retried {0} times.", actualResponse.RetryCount) });
            }

            requestResults.AddResults(
                new ValidationError[]
                { new ValidationMessage(null, "HTTP Response:\r\n{0}", actualResponse.FullText(false)) });
            requestResults.Duration = actualMethodDuration;

            // Perform validation on the method's actual response
            method.ValidateResponse(actualResponse, expectedResponse, scenario, issues, options);

            requestResults.AddResults(issues.Issues.ToArray());

            // TODO: If the method is defined as a long running operation, we need to go poll the status
            // URL to make sure that the operation finished and the response type is valid.

            if (issues.Issues.WereErrors())
            {
                results.SetOutcome(actionName, ValidationOutcome.Error);
            }
            else if (issues.Issues.WereWarnings())
            {
                results.SetOutcome(actionName, ValidationOutcome.Warning);
            }
            else
            {
                results.SetOutcome(actionName, ValidationOutcome.Passed);
            }
        }
 public void SendRequest(string request)
 {
     http.RequestBody = request;
     response         = http.Post();
 }
Пример #55
0
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream   myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br     = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;

                    long fileLength = myFile.Length;
                    long startBytes = 0;
                    int  pack       = 10240; //10K bytes
                    int  sleep      = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;

                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }

                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return(false);
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
        public T GetAcsResponse <T>(AcsRequest <T> request, IClientProfile profile) where T : AcsResponse
        {
            HttpResponse httpResponse = this.DoAction(request, profile);

            return(ParseAcsResponse(request, httpResponse));
        }
Пример #57
0
 /* goodG2B() - use goodsource and badsink */
 private static void GoodG2B(HttpRequest req, HttpResponse resp)
 {
     /* FIX: Use a hardcoded string */
     data = "foo";
     CWE89_SQL_Injection__Web_Connect_tcp_ExecuteScalar_68b.GoodG2BSink(req, resp);
 }
Пример #58
0
        /// <summary>
        /// 文件下载方法2
        /// </summary>
        /// <param name="request">request对象</param>
        /// <param name="response">response对象</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="fullPath">文件路径</param>
        /// <param name="speed">间隔</param>
        /// <returns></returns>
        public static bool ResponseFile(HttpRequest request, HttpResponse response, string fileName, string fullPath, long speed)
        {
            if (speed == 0L)
            {
                speed = 0xfa000L;
            }
            try
            {
                string tagetPath = HttpContext.Current.Server.MapPath("/uploadfiles/" + Guid.NewGuid() + Path.GetExtension(fullPath));
                File.Copy(fullPath, tagetPath);
                fullPath = tagetPath;
                var myFile = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var br     = new BinaryReader(myFile);
                try
                {
                    response.AddHeader("Accept-Ranges", "bytes");
                    response.Buffer = false;
                    long      fileLength = myFile.Length;
                    long      startBytes = 0L;
                    const int pack       = 0x2800;
// ReSharper disable PossibleLossOfFraction
                    int sleep = ((int)Math.Floor((decimal)(0x3e8 * pack / speed))) + 1;
// ReSharper restore PossibleLossOfFraction
                    if (request.Headers["Range"] != null)
                    {
                        response.StatusCode = 0xce;
                        startBytes          = Convert.ToInt64(request.Headers["Range"].Split(new[] { '=', '-' })[1]);
                    }
                    response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0L)
                    {
                        response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1L, fileLength));
                    }
                    response.AddHeader("Connection", "Keep-Alive");
                    response.ContentType = "application/octet-stream";
                    response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    // ReSharper disable PossibleLossOfFraction
                    int maxCount = ((int)Math.Floor((decimal)((fileLength - startBytes) / pack))) + 1;
                    // ReSharper restore PossibleLossOfFraction
                    for (int i = 0; i < maxCount; i++)
                    {
                        if (response.IsClientConnected)
                        {
                            response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch (IOException oE)
                {
                    string str = oE.Message;
                    return(false);
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                    try
                    {
                        File.Delete(fullPath);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Пример #59
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            #region Request
            // Set base URL
            var localUrl = ReplaceValues(url, data);
            var cType    = ReplaceValues(contentType, data);
            var oldJar   = data.Cookies;

            // Create request
            HttpRequest request = new HttpRequest();

            // Setup options
            var timeout = data.GlobalSettings.General.RequestTimeout * 1000;
            request.IgnoreProtocolErrors         = true;
            request.AllowAutoRedirect            = autoRedirect;
            request.EnableEncodingContent        = acceptEncoding;
            request.ReadWriteTimeout             = timeout;
            request.ConnectTimeout               = timeout;
            request.KeepAlive                    = true;
            request.MaximumAutomaticRedirections = data.ConfigSettings.MaxRedirects;

            // Check if it has GET parameters
            if (ParseQuery && localUrl.Contains('?') && localUrl.Contains('='))
            {
                // Remove the query from the base URL
                localUrl = ReplaceValues(url.Split('?')[0], data);
                data.Log(new LogEntry($"Calling Base URL: {localUrl}", Colors.MediumTurquoise));

                // Parse the GET parameters
                var getParams = ReplaceValues(url.Split('?')[1], data);
                var paramList = getParams.Split('&');

                // Build the query, first replace variables in them and encode the parameters
                foreach (var par in paramList)
                {
                    var split = par.Split('=');

                    // Encode them if needed
                    if (split[0].Contains('%'))
                    {
                        split[0] = Uri.EscapeDataString(split[0]);
                    }
                    if (split[1].Contains('%'))
                    {
                        split[1] = Uri.EscapeDataString(split[1]);
                    }

                    // Add them to the query
                    request.AddUrlParam(split[0], split[1]);

                    data.Log(new LogEntry($"Added Query Parameter: {split[0]} = {split[1]}", Colors.MediumTurquoise));
                }
            }
            else
            {
                data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise));
            }

            // Set up the Content and Content-Type
            HttpContent content = null;
            switch (requestType)
            {
            case RequestType.Standard:
                var pData = ReplaceValues(Regex.Replace(postData, @"(?<!\\)\\n", Environment.NewLine).Replace(@"\\n", @"\n"), data);

                if (CanContainBody(method))
                {
                    if (encodeContent)
                    {
                        // Very dirty but it works
                        var nonce = data.Random.Next(1000000, 9999999);
                        pData = pData.Replace("&", $"{nonce}&{nonce}").Replace("=", $"{nonce}={nonce}");
                        pData = System.Uri.EscapeDataString(pData).Replace($"{nonce}%26{nonce}", "&").Replace($"{nonce}%3D{nonce}", "=");
                    }

                    content             = new StringContent(pData);
                    content.ContentType = cType;
                    data.Log(new LogEntry($"Post Data: {pData}", Colors.MediumTurquoise));
                }
                break;

            case RequestType.Multipart:
                var bdry = multipartBoundary != "" ? ReplaceValues(multipartBoundary, data) : GenerateMultipartBoundary();
                content = new Extreme.Net.MultipartContent(bdry);
                var mContent = content as Extreme.Net.MultipartContent;
                data.Log(new LogEntry($"Content-Type: multipart/form-data; boundary={bdry}", Colors.MediumTurquoise));
                data.Log(new LogEntry("Multipart Data:", Colors.MediumTurquoise));
                data.Log(new LogEntry(bdry, Colors.MediumTurquoise));
                foreach (var c in MultipartContents)
                {
                    var rValue       = ReplaceValues(c.Value, data);
                    var rName        = ReplaceValues(c.Name, data);
                    var rContentType = ReplaceValues(c.ContentType, data);

                    if (c.Type == MultipartContentType.String)
                    {
                        mContent.Add(new StringContent(rValue), rName);
                        data.Log(new LogEntry($"Content-Disposition: form-data; name=\"{rName}\"{Environment.NewLine}{Environment.NewLine}{rValue}", Colors.MediumTurquoise));
                    }
                    else if (c.Type == MultipartContentType.File)
                    {
                        mContent.Add(new FileContent(rValue), rName, rValue, rContentType);
                        data.Log(new LogEntry($"Content-Disposition: form-data; name=\"{rName}\"; filename=\"{rValue}\"{Environment.NewLine}Content-Type: {rContentType}{Environment.NewLine}{Environment.NewLine}[FILE CONTENT OMITTED]", Colors.MediumTurquoise));
                    }
                    data.Log(new LogEntry(bdry, Colors.MediumTurquoise));
                }
                break;

            default:
                break;
            }

            // Set proxy
            if (data.UseProxies)
            {
                request.Proxy = data.Proxy.GetClient();

                try
                {
                    request.Proxy.ReadWriteTimeout = timeout;
                    request.Proxy.ConnectTimeout   = timeout;
                    request.Proxy.Username         = data.Proxy.Username;
                    request.Proxy.Password         = data.Proxy.Password;
                }
                catch { }
            }

            // Set headers
            data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise));
            // var fixedNames = Enum.GetNames(typeof(HttpHeader)).Select(n => n.ToLower());
            foreach (var header in CustomHeaders)
            {
                try
                {
                    var key         = ReplaceValues(header.Key, data);
                    var replacedKey = key.Replace("-", "").ToLower(); // Used to compare with the HttpHeader enum
                    var val         = ReplaceValues(header.Value, data);

                    if (replacedKey == "contenttype" && content != null)
                    {
                        continue;
                    }                                                                  // Disregard additional Content-Type headers
                    if (replacedKey == "acceptencoding" && acceptEncoding)
                    {
                        continue;
                    }                                                                    // Disregard additional Accept-Encoding headers
                    // else if (fixedNames.Contains(replacedKey)) request.AddHeader((HttpHeader)Enum.Parse(typeof(HttpHeader), replacedKey, true), val);
                    else
                    {
                        request.AddHeader(key, val);
                    }

                    data.Log(new LogEntry(key + ": " + val, Colors.MediumTurquoise));
                }
                catch { }
            }

            // Add the authorization header on a Basic Auth request
            if (requestType == RequestType.BasicAuth)
            {
                var usr  = ReplaceValues(authUser, data);
                var pwd  = ReplaceValues(authPass, data);
                var auth = "Basic " + BlockFunction.Base64Encode(usr + ":" + pwd);
                request.AddHeader("Authorization", auth);
                data.Log(new LogEntry($"Authorization: {auth}", Colors.MediumTurquoise));
            }

            // Add the content-type header
            if (CanContainBody(method) && content != null && requestType == RequestType.Standard)
            {
                data.Log(new LogEntry($"Content-Type: {cType}", Colors.MediumTurquoise));
            }

            // Add new user-defined custom cookies to the bot's cookie jar
            request.Cookies = new CookieDictionary();
            foreach (var cookie in CustomCookies)
            {
                data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data);
            }

            // Set cookies from the bot's cookie jar to the request's CookieDictionary
            data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));
            foreach (var cookie in data.Cookies)
            {
                request.Cookies.Add(cookie.Key, cookie.Value);
                data.Log(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise));
            }

            data.LogNewLine();
            #endregion

            #region Response
            // Create the response
            HttpResponse response = null;

            try
            {
                // Get response
                response = request.Raw(method, localUrl, content);
                var responseString = "";

                // Get address
                data.Address = response.Address.ToString();
                data.Log(new LogEntry("Address: " + data.Address, Colors.Cyan));

                // Get code
                data.ResponseCode = ((int)response.StatusCode).ToString();
                data.Log(new LogEntry($"Response code: {data.ResponseCode} ({response.StatusCode})", Colors.Cyan));

                // Get headers
                data.Log(new LogEntry("Received headers:", Colors.DeepPink));
                var headerList      = new List <KeyValuePair <string, string> >();
                var receivedHeaders = response.EnumerateHeaders();
                data.ResponseHeaders.Clear();
                while (receivedHeaders.MoveNext())
                {
                    var header = receivedHeaders.Current;
                    data.ResponseHeaders.Add(header.Key, header.Value);
                    data.Log(new LogEntry($"{header.Key}: {header.Value}", Colors.LightPink));
                }
                if (!response.ContainsHeader(HttpHeader.ContentLength) && ResponseType != ResponseType.File)
                {
                    responseString = response.ToString(); // Read the stream

                    if (data.ResponseHeaders.ContainsKey("Content-Encoding") && data.ResponseHeaders["Content-Encoding"].Contains("gzip"))
                    {
                        data.ResponseHeaders["Content-Length"] = GZip.Zip(responseString).Length.ToString();
                    }
                    else
                    {
                        data.ResponseHeaders["Content-Length"] = responseString.Length.ToString();
                    }

                    data.Log(new LogEntry($"Content-Length: {data.ResponseHeaders["Content-Length"]}", Colors.LightPink));
                }

                // Get cookies
                data.Log(new LogEntry("Received cookies:", Colors.Goldenrod));
                data.Cookies = response.Cookies;
                foreach (var cookie in response.Cookies)
                {
                    // If the cookie was already present before, don't log it
                    if (oldJar.ContainsKey(cookie.Key) && oldJar[cookie.Key] == cookie.Value)
                    {
                        continue;
                    }

                    data.Log(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.LightGoldenrodYellow));
                }

                // Save the response content
                switch (responseType)
                {
                case ResponseType.String:
                    data.Log(new LogEntry("Response Source:", Colors.Green));
                    if (readResponseSource)
                    {
                        if (responseString == "")
                        {
                            responseString = response.ToString();                           // Read the stream if you didn't already read it
                        }
                        data.ResponseSource = responseString;
                        data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow));
                    }
                    else
                    {
                        data.ResponseSource = "";
                        data.Log(new LogEntry("[SKIPPED]", Colors.GreenYellow));
                    }
                    break;

                case ResponseType.File:
                    if (SaveAsScreenshot)
                    {
                        SaveScreenshot(response.ToMemoryStream(), data);     // Read the stream
                        data.Log(new LogEntry("File saved as screenshot", Colors.Green));
                    }
                    else
                    {
                        var filePath = ReplaceValues(downloadPath, data);
                        var dirName  = Path.GetDirectoryName(filePath);
                        if (dirName != "")
                        {
                            dirName += Path.DirectorySeparatorChar.ToString();
                        }
                        var fileName      = Path.GetFileNameWithoutExtension(filePath);
                        var fileExtension = Path.GetExtension(filePath);
                        var sanitizedPath = $"{dirName}{MakeValidFileName(fileName)}{fileExtension}";
                        using (var stream = File.Create(sanitizedPath)) { response.ToMemoryStream().CopyTo(stream); }     // Read the stream
                        data.Log(new LogEntry("File saved as " + sanitizedPath, Colors.Green));
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                data.Log(new LogEntry(ex.Message, Colors.White));
                if (ex.GetType() == typeof(HttpException))
                {
                    data.ResponseCode = ((HttpException)ex).HttpStatusCode.ToString();
                    data.Log(new LogEntry("Status code: " + data.ResponseCode, Colors.Cyan));
                }

                if (!data.ConfigSettings.IgnoreResponseErrors)
                {
                    throw;
                }
            }
            #endregion
        }
        public T GetAcsResponse <T>(AcsRequest <T> request) where T : AcsResponse
        {
            HttpResponse httpResponse = this.DoAction(request);

            return(ParseAcsResponse(request, httpResponse));
        }