Beispiel #1
0
        public async Task <ProxyContent> Dispatch(string forwardUrl, HttpRequest incomingRequest, HeaderDictionary additionalHeaders = null)
        {
            var result   = new ProxyContent();
            var outbound = (HttpWebRequest)HttpWebRequest.Create(forwardUrl);

            outbound.CookieContainer = new CookieContainer();
            outbound.Method          = incomingRequest.Method;
            outbound.ContentType     = incomingRequest.ContentType;
            if (additionalHeaders != null)
            {
                foreach (var h in additionalHeaders)
                {
                    outbound.Headers.Add(h.Key, h.Value.ToString());
                }
            }
            foreach (var h in incomingRequest.Headers)
            {
                if (!WebHeaderCollection.IsRestricted(h.Key))
                {
                    outbound.Headers[h.Key] = incomingRequest.Headers[h.Key];
                }
            }
            if (incomingRequest.Method != "GET" &&
                incomingRequest.Method != "HEAD" &&
                incomingRequest.ContentLength > 0)
            {
                var outboundBody = outbound.GetRequestStream();
                incomingRequest.Body.CopyTo(outboundBody);
                outboundBody.Close();
            }
            try
            {
                using (var response = (HttpWebResponse)await outbound.GetResponseAsync())
                {
                    var receiveStream = response.GetResponseStream();
                    using (var memoryStream = new MemoryStream()){
                        await receiveStream.CopyToAsync(memoryStream);

                        result.Content = memoryStream.ToArray();
                    }
                    result.ContentType = response.ContentType;
                    foreach (var h in response.Headers.AllKeys)
                    {
                        if (!WebHeaderCollection.IsRestricted(h))
                        {
                            result.Headers.Add(h, response.Headers[h]);
                        }
                    }
                    foreach (Cookie cookie in response.Cookies)
                    {
                        result.Cookies.Add(cookie);
                    }
                }
            }
            catch (WebException ex)
            {
                result.Success    = false;
                result.HTTPStatus = 500;
                if (ex.Status == WebExceptionStatus.ProtocolError &&
                    ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    result.HTTPStatus = (int)resp.StatusCode;
                }
            }
            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// Creates a HttpWebRequest form the specified HttpRequestBase object.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static HttpWebRequest CreateWebRequest(HttpRequestBase request, Uri url)
        {
            string         value = null;
            HttpWebRequest web   = (HttpWebRequest)WebRequest.Create(url ?? request.Url);

            NameValueCollection headers = request.Headers;

            foreach (string name in headers.Keys)
            {
                if (!WebHeaderCollection.IsRestricted(name))
                {
                    try {
                        web.Headers[name] = headers[name];
                    } catch (ArgumentException) {
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Accept"]))
            {
                try {
                    web.Accept = value;
                } catch (ArgumentException) {
                    web.Accept = "*/*";
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Connection"]))
            {
                value = value.ToLower();
                try {
                    if (value.Contains("keep-alive"))
                    {
                        web.KeepAlive = true;
                    }
                    else if (value.Contains("close"))
                    {
                        web.KeepAlive = false;
                    }
                    else
                    {
                        web.Connection = value;
                    }
                } catch (ArgumentException) {
                    web.KeepAlive = true;
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Content-Length"]))
            {
                long length = 0;
                if (long.TryParse(value, out length))
                {
                    web.ContentLength = length;
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Content-Type"]))
            {
                web.ContentType = value;
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Date"]))
            {
                DateTime date;
                if (DateTime.TryParse(value, out date))
                {
                    web.Date = date;
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Expect"]))
            {
                if (!(web.ServicePoint.Expect100Continue = value.ToLower().Contains("100-continue")))
                {
                    web.Expect = value;
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["If-Modified-Since"]))
            {
                DateTime time;
                if (DateTime.TryParse(value, out time))
                {
                    web.IfModifiedSince = time;
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Referer"]))
            {
                try {
                    web.Referer = Uri.EscapeUriString(value);
                } catch (ArgumentException) {
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Transfer-Encoding"]))
            {
                try {
                    web.TransferEncoding = value;
                } catch (ArgumentException) {
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["User-Agent"]))
            {
                try {
                    web.UserAgent = value;
                } catch (ArgumentException) {
                    web.UserAgent = "MSIE9.0";
                }
            }

            if (!string.IsNullOrWhiteSpace(value = headers["Transfer-Encoding"]))
            {
                switch (value.ToLower())
                {
                case "chunked":
                    web.SendChunked = true;
                    break;

                default:
                    web.SendChunked = false;
                    break;
                }
            }

            Cookie          cookie          = null;
            CookieContainer cookieContainer = web.CookieContainer = new CookieContainer();

            foreach (string name in request.Cookies.AllKeys)
            {
                try {
                    cookie        = WebCookieToNetCookie(request.Cookies[name]);
                    cookie.Domain = web.RequestUri.Host;
                    cookieContainer.Add(cookie);
                } catch (CookieException) {
                }
            }

            web.SetForwardedIP(request);
            web.ServicePoint.Expect100Continue = false;
            web.ProtocolVersion = HttpVersion.Version11;
            web.Method          = request.HttpMethod;

            return(web);
        }
Beispiel #3
0
        private void WriteMetadata(RavenJObject metadata)
        {
            if (metadata == null || metadata.Count == 0)
            {
                webRequest.ContentLength = 0;
                return;
            }

            foreach (var prop in metadata)
            {
                if (prop.Value == null)
                {
                    continue;
                }

                if (prop.Value.Type == JTokenType.Object ||
                    prop.Value.Type == JTokenType.Array)
                {
                    continue;
                }

                var headerName = prop.Key;
                if (headerName == "ETag")
                {
                    headerName = "If-None-Match";
                }
                var value = prop.Value.Value <object>().ToString();

                // Restricted headers require their own special treatment, otherwise an exception will
                // be thrown.
                // See http://msdn.microsoft.com/en-us/library/78h415ay.aspx
                if (WebHeaderCollection.IsRestricted(headerName))
                {
                    switch (headerName)
                    {
                    /*case "Date":
                     * case "Referer":
                     * case "Content-Length":
                     * case "Expect":
                     * case "Range":
                     * case "Transfer-Encoding":
                     * case "User-Agent":
                     * case "Proxy-Connection":
                     * case "Host": // Host property is not supported by 3.5
                     *      break;*/
                    case "Content-Type":
                        webRequest.ContentType = value;
                        break;

                    case "If-Modified-Since":
                        DateTime tmp;
                        DateTime.TryParse(value, out tmp);
                        webRequest.IfModifiedSince = tmp;
                        break;

                    case "Accept":
                        webRequest.Accept = value;
                        break;

                    case "Connection":
                        webRequest.Connection = value;
                        break;
                    }
                }
                else
                {
                    webRequest.Headers[headerName] = value;
                }
            }
        }
        public static void SimpleListenerExample(string[] prefixes)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            string proxyAddress = "http://localhost:5000";

            if (prefixes[1] != null)
            {
                proxyAddress = prefixes[1];
                add          = proxyAddress;
                HttpWebRequest  t = (HttpWebRequest)WebRequest.Create(proxyAddress + "/swagger/v1/swagger.json");
                HttpWebResponse r = (HttpWebResponse)t.GetResponse();
                swagger = new StreamReader(r.GetResponseStream()).ReadToEnd();
            }
            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            listener.Prefixes.Add(prefixes[0]);
            Generate.Initializer();
            listener.Start();
            while (true)
            {
                Console.WriteLine("\nListening...\n");
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                if (request.RawUrl.ToLower().Equals("/generate/csharp"))
                {
                    HttpListenerResponse response1 = context.Response;
                    // Construct a response.
                    string responseString1 = Generate.generate();
                    Console.WriteLine("Code Generated\n");
                    byte[] buffer1 = Encoding.UTF8.GetBytes(responseString1);
                    // Get a response stream and write the response to it.
                    response1.ContentLength64 = buffer1.Length;
                    Stream output1 = response1.OutputStream;
                    output1.Write(buffer1, 0, buffer1.Length);
                    continue;
                }
                // Obtain a response object.
                string          method = request.HttpMethod;
                HttpWebRequest  pRequest;
                string          k;
                HttpWebResponse res    = null;
                Record          record = new Record();
                record.req.path = request.RawUrl;
                pRequest        = (HttpWebRequest)WebRequest.Create(proxyAddress + request.RawUrl);
                Console.WriteLine(proxyAddress + request.RawUrl);
                foreach (var x in request.Headers.Keys)
                {
                    string key   = x.ToString();
                    string value = request.Headers.Get(x.ToString());
                    if (!WebHeaderCollection.IsRestricted(x.ToString()))
                    {
                        pRequest.Headers.Add(key, value);
                    }
                    record.req.Headers.Add(key, value);
                }

                pRequest.Method      = method;
                record.req.method    = method;
                pRequest.ContentType = request.ContentType;
                Stream       body     = request.InputStream;
                Encoding     encoding = request.ContentEncoding;
                StreamReader reader   = new System.IO.StreamReader(body, encoding);
                string       Body     = reader.ReadToEnd();
                record.req.body = Body;
                reader.Close();
                if (!method.Equals("GET"))
                {
                    pRequest.GetRequestStream().Write(Encoding.ASCII.GetBytes(Body), 0, Body.Length);
                }
                try
                {
                    res = (HttpWebResponse)pRequest.GetResponse();
                    k   = new StreamReader(res.GetResponseStream()).ReadToEnd();
                    record.res.statusCode = (int)res.StatusCode;
                    record.res.body       = k;
                    //to record request and response
                    MemoryStream ms = new MemoryStream();
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Record));
                    ser.WriteObject(ms, record);
                    byte[] json = ms.ToArray();
                    ms.Close();
                    string rec = Encoding.UTF8.GetString(json, 0, json.Length).Replace("\\/", "/");
                    rec = rec.Replace("\u000d", "\r");
                    rec = rec.Replace("\u000a", ",");
                    StreamWriter file = File.AppendText("Generates.json");
                    file.WriteLine(rec);
                    file.Close();
                    Console.WriteLine("Recorded...\n");
                }
                catch (Exception e)
                {
                    k = "ERROR 404" + e.Message;
                }

                HttpListenerResponse response = context.Response;
                // Construct a response.
                string responseString = k;
                if (k == null)
                {
                    responseString = "Empty body";
                }
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
            }
        }
Beispiel #5
0
        public HttpWebRequest PrepareHttpWebRequest(string baseUrl)
        {
            var effectiveUrl = GenerateAbsoluteUrl(baseUrl);

            this.LastEffectiveUri = effectiveUrl;

            HttpWebRequest request = WebRequest.CreateHttp(effectiveUrl);

            request.AllowAutoRedirect = false;
            request.Method            = this.Method;
            request.KeepAlive         = true;
            request.ServicePoint.Expect100Continue = false;
            request.Credentials = this.Credentials;

            foreach (var key in this.Headers.AllKeys)
            {
                if (IgnoredHeaders.Contains(key.ToLower()))
                {
                    continue;
                }

                if (WebHeaderCollection.IsRestricted(key))
                {
                    switch (key.ToLower())
                    {
                    case "accept":
                        request.Accept = this.Headers[key];
                        break;

                    case "content-type":
                        request.ContentType = this.Headers[key];
                        break;

                    case "connection":
                        request.Connection = this.Headers[key];
                        break;

                    case "date":
                        request.Date = DateTime.Parse(this.Headers[key]);
                        break;

                    case "expect":
                        request.Expect = this.Headers[key];
                        break;

                    case "host":
                        request.Host = this.Headers[key];
                        break;

                    case "if-modified-since":
                        request.IfModifiedSince = this.Headers[key].Equals("current_time") ? DateTime.Now : Convert.ToDateTime(this.Headers[key]);
                        break;

                    case "range":
                        AddRangeHeader(request, this.Headers[key]);
                        break;

                    case "referer":
                        request.Referer = this.Headers[key];
                        break;

                    case "transfer-encoding":
                        request.TransferEncoding = this.Headers[key];
                        break;

                    case "user-agent":
                        request.UserAgent = this.Headers[key];
                        break;

                    case "proxy-connection":
                    default:
                        throw new NotSupportedException(string.Format("Header {0} is a restricted header and is not supported.", key));
                    }
                }
                else
                {
                    request.Headers.Add(key, this.Headers[key]);
                }
            }

            if (this.Body != null && this.BodyBytes == null)
            {
                using (var stream = request.GetRequestStream())
                {
                    var writer = new StreamWriter(stream);
                    writer.Write(this.Body);
                    writer.Flush();
                }
            }
            else if (this.Body == null && this.BodyBytes != null)
            {
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(this.BodyBytes, 0, this.BodyBytes.Length);
                }
            }
            else if (this.Body != null && this.BodyBytes != null)
            {
                throw new InvalidOperationException("Body and BodyBytes cannot both be set on the same request");
            }

            if (null != ValidationConfig.AdditionalHttpHeaders)
            {
                foreach (var header in ValidationConfig.AdditionalHttpHeaders)
                {
                    request.Headers.Add(header);
                }
            }

            return(request);
        }
Beispiel #6
0
        void BeginProcessRequest(HttpChannelRequestAsyncResult result)
        {
            Message  message = result.Message;
            TimeSpan timeout = result.Timeout;
            // FIXME: is distination really like this?
            Uri destination = message.Headers.To;

            if (destination == null)
            {
                if (source.Transport.ManualAddressing)
                {
                    throw new InvalidOperationException("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
                }
                else
                {
                    destination = Via ?? RemoteAddress.Uri;
                }
            }

            var web_request = (HttpWebRequest)HttpWebRequest.Create(destination);

            web_requests.Add(web_request);
            result.WebRequest       = web_request;
            web_request.Method      = "POST";
            web_request.ContentType = Encoder.ContentType;
            HttpWebRequest hwr  = (web_request as HttpWebRequest);
            var            cmgr = source.GetProperty <IHttpCookieContainerManager> ();

            if (cmgr != null)
            {
                hwr.CookieContainer = cmgr.CookieContainer;
            }

            // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
            var    httpbe   = (HttpTransportBindingElement)source.Transport;
            string authType = null;

            switch (httpbe.AuthenticationScheme)
            {
            // AuthenticationSchemes.Anonymous is the default, ignored.
            case AuthenticationSchemes.Basic:
                authType = "Basic";
                break;

            case AuthenticationSchemes.Digest:
                authType = "Digest";
                break;

            case AuthenticationSchemes.Ntlm:
                authType = "Ntlm";
                break;

            case AuthenticationSchemes.Negotiate:
                authType = "Negotiate";
                break;
            }
            if (authType != null)
            {
                var    cred = source.ClientCredentials;
                string user = cred != null ? cred.UserName.UserName : null;
                string pwd  = cred != null ? cred.UserName.Password : null;
                if (String.IsNullOrEmpty(user))
                {
                    throw new InvalidOperationException(String.Format("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
                }
                var nc = new NetworkCredential(user, pwd);
                web_request.Credentials = nc;
                // FIXME: it is said required in SL4, but it blocks full WCF.
                //web_request.UseDefaultCredentials = false;
            }

            web_request.Timeout = (int)timeout.TotalMilliseconds;

            // There is no SOAP Action/To header when AddressingVersion is None.
            if (message.Version.Envelope.Equals(EnvelopeVersion.Soap11) ||
                message.Version.Addressing.Equals(AddressingVersion.None))
            {
                if (message.Headers.Action != null)
                {
                    web_request.Headers ["SOAPAction"] = String.Concat("\"", message.Headers.Action, "\"");
                    message.Headers.RemoveAll("Action", message.Version.Addressing.Namespace);
                }
            }

            // apply HttpRequestMessageProperty if exists.
            bool   suppressEntityBody = false;
            string pname = HttpRequestMessageProperty.Name;

            if (message.Properties.ContainsKey(pname))
            {
                HttpRequestMessageProperty hp = (HttpRequestMessageProperty)message.Properties [pname];
                foreach (var key in hp.Headers.AllKeys)
                {
                    if (WebHeaderCollection.IsRestricted(key))                        // do not ignore this. WebHeaderCollection rejects restricted ones.
                    // FIXME: huh, there should be any better way to do such stupid conversion.
                    {
                        switch (key)
                        {
                        case "Accept":
                            web_request.Accept = hp.Headers [key];
                            break;

                        case "Connection":
                            web_request.Connection = hp.Headers [key];
                            break;

                        //case "ContentLength":
                        //	web_request.ContentLength = hp.Headers [key];
                        //	break;
                        case "ContentType":
                            web_request.ContentType = hp.Headers [key];
                            break;

                        //case "Date":
                        //	web_request.Date = hp.Headers [key];
                        //	break;
                        case "Expect":
                            web_request.Expect = hp.Headers [key];
                            break;

                        case "Host":
                            web_request.Host = hp.Headers [key];
                            break;

                        //case "If-Modified-Since":
                        //	web_request.IfModifiedSince = hp.Headers [key];
                        //	break;
                        case "Referer":
                            web_request.Referer = hp.Headers [key];
                            break;

                        case "Transfer-Encoding":
                            web_request.TransferEncoding = hp.Headers [key];
                            break;

                        case "User-Agent":
                            web_request.UserAgent = hp.Headers [key];
                            break;
                        }
                    }
                    else
                    {
                        web_request.Headers [key] = hp.Headers [key];
                    }
                }
                web_request.Method = hp.Method;
                // FIXME: do we have to handle hp.QueryString ?
                if (hp.SuppressEntityBody)
                {
                    suppressEntityBody = true;
                }
            }

#if !MOBILE
            if (source.ClientCredentials != null)
            {
                var cred = source.ClientCredentials;
                if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null))
                {
                    ((HttpWebRequest)web_request).ClientCertificates.Add(cred.ClientCertificate.Certificate);
                }
            }
#endif

            if (!suppressEntityBody && String.Compare(web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0)
            {
                MemoryStream buffer = new MemoryStream();
                Encoder.WriteMessage(message, buffer);

                if (buffer.Length > int.MaxValue)
                {
                    throw new InvalidOperationException("The argument message is too large.");
                }

                web_request.ContentLength = (int)buffer.Length;

                web_request.BeginGetRequestStream(delegate(IAsyncResult r) {
                    try {
                        result.CompletedSynchronously &= r.CompletedSynchronously;
                        using (Stream s = web_request.EndGetRequestStream(r))
                            s.Write(buffer.GetBuffer(), 0, (int)buffer.Length);
                        web_request.BeginGetResponse(GotResponse, result);
                    } catch (WebException ex) {
                        switch (ex.Status)
                        {
                        case WebExceptionStatus.NameResolutionFailure:
                        case WebExceptionStatus.ConnectFailure:
                            result.Complete(new EndpointNotFoundException(new EndpointNotFoundException().Message, ex));
                            break;

                        default:
                            result.Complete(ex);
                            break;
                        }
                    } catch (Exception ex) {
                        result.Complete(ex);
                    }
                }, null);
            }
            else
            {
                web_request.BeginGetResponse(GotResponse, result);
            }
        }
        /// <summary>
        /// Helper method to execute the request
        /// </summary>
        protected virtual HttpWebResponse SendRequest(ApiRequest apiRequest, Dictionary <string, string> postSignedHeaders)
        {
            string path = apiRequest.Path.ToString();

            // add the query parameters to the URL, if there are any
            if (apiRequest.QueryParameters != null && apiRequest.QueryParameters.Count > 0)
            {
                var canonicalBuilder = new CanonicalBuilder();
                path += "?" + canonicalBuilder.GetCanonicalizedQueryString(apiRequest.QueryParameters);
            }

            // TODO: move setting of SecurityProtocol into constructor

            // ensure the right minimum TLS version is being used
            if (Util.IsObsoleteSecurityProtocol(ServicePointManager.SecurityProtocol))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            }

            // TODO: consider switching to HttpClient class for web requests

            // create the web request
            HttpWebRequest request = WebRequest.Create(path) as HttpWebRequest;

            foreach (KeyValuePair <string, string> header in postSignedHeaders)
            {
                if (WebHeaderCollection.IsRestricted(header.Key))
                {
                    switch (header.Key)
                    {
                    case "accept":
                        request.Accept = header.Value;
                        break;

                    case "content-type":
                        request.ContentType = header.Value;
                        break;

                    case "user-agent":
                        request.UserAgent = header.Value;
                        break;

                    default:
                        throw new AmazonPayClientException("unknown header" + " " + header.Key);
                    }
                }
                else
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
            request.Method = apiRequest.HttpMethod.ToString();

            if (apiRequest.HttpMethod != HttpMethod.GET)
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(apiRequest.Body.ToJson());
                    streamWriter.Flush();
                }
            }

            HttpWebResponse httpResponse;

            try
            {
                httpResponse = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException we)
            {
                httpResponse = (HttpWebResponse)we.Response as HttpWebResponse;

                if (httpResponse == null)
                {
                    throw new AmazonPayClientException("Http Response is empty " + we);
                }
            }

            return(httpResponse);
        }
Beispiel #8
0
        private static TypeTo AddHeaders <TypeFrom, TypeTo>(TypeFrom headersFrom, HttpWebRequest webRequest)
            where TypeFrom : NameValueCollection
            where TypeTo : NameValueCollection, new()
        {
            TypeTo webHeaders = new TypeTo();

            foreach (var key in headersFrom.AllKeys)
            {
                var setValue = true;

                if (webHeaders is WebHeaderCollection && webRequest != null)
                {
                    WebHeaderCollection convertTo = webHeaders as WebHeaderCollection;

                    if (WebHeaderCollection.IsRestricted(key))
                    {
                        var currentKey = key.ToLower().Trim();
                        var lookup     = new Tuple <string, string> [13];
                        lookup[0]  = new Tuple <string, string>("accept", "Accept");
                        lookup[1]  = new Tuple <string, string>("connection", "Connection");
                        lookup[2]  = new Tuple <string, string>("content-length", "ContentLength");
                        lookup[3]  = new Tuple <string, string>("content-type", "ContentType");
                        lookup[4]  = new Tuple <string, string>("date", "Date");
                        lookup[5]  = new Tuple <string, string>("expect", "Expect");
                        lookup[6]  = new Tuple <string, string>("host", "Host");
                        lookup[7]  = new Tuple <string, string>("if-modified-since", "IfModifiedSince");
                        lookup[8]  = new Tuple <string, string>("range", "Range");
                        lookup[9]  = new Tuple <string, string>("referrer", "Referrer");
                        lookup[10] = new Tuple <string, string>("transfer-encoding", "TransferEncoding");
                        lookup[11] = new Tuple <string, string>("user-agent", "UserAgent");
                        lookup[11] = new Tuple <string, string>("proxy-connection", "KeepAlive");

                        var match = lookup.FirstOrDefault(x => x.Item1 == currentKey);

                        if (match != null)
                        {
                            setValue = false;

                            try
                            {
                                if (headersFrom[key].ToLower() == "keep-alive")
                                {
                                    webRequest.GetType().InvokeMember("KeepAlive", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, webRequest, new object[] { true });
                                }
                                else
                                {
                                    webRequest.GetType().InvokeMember(match.Item2, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, webRequest, new object[] { headersFrom[key] });
                                }
                            }
                            catch (Exception) { }
                        }
                    }
                }

                if (setValue)
                {
                    try
                    {
                        if (Array.IndexOf(webHeaders.AllKeys, key) != -1)
                        {
                            webHeaders[key] = headersFrom[key];
                        }
                        else
                        {
                            webHeaders.Add(key, headersFrom[key]);
                        }
                    }
                    catch (Exception) { }
                }
            }

            return(webHeaders);
        }
        private static void UpdateContextResponse(HttpContext context, HttpWebResponse response, string path, string GUID)
        {
            try
            {
                // Copy headers
                foreach (var headerKey in response.Headers.AllKeys)
                {
                    if (WebHeaderCollection.IsRestricted(headerKey))
                    {
                        continue;
                    }
                    context.Response.AddHeader(headerKey, response.Headers[headerKey]);
                }
                context.Response.ContentType = response.ContentType;
                context.Response.Cookies.Clear();

                foreach (Cookie receivedCookie in response.Cookies)
                {
                    var c = new HttpCookie(receivedCookie.Name,
                                           receivedCookie.Value)
                    {
                        Domain   = context.Request.Url.Host,
                        Expires  = receivedCookie.Expires,
                        HttpOnly = receivedCookie.HttpOnly,
                        Path     = receivedCookie.Path,
                        Secure   = receivedCookie.Secure
                    };
                    context.Response.Cookies.Add(c);
                }
                var responseData = GetResponseStreamBytes(response);
                if ((path.Contains("Document") && path.Contains("MarkupBurner") && context.Request.Url.Query.Contains("GUID") == true))
                {
                    string EncryptID = System.Web.HttpUtility.UrlDecode(context.Request.UrlReferrer.AbsoluteUri.Split('?')[1].Substring(7)).Replace(' ', '+');
                    int    ID        = Convert.ToInt32(EncryptDecrypt.Decrypt(EncryptID));
                    string OrderNo   = string.Empty;
                    string PartNo    = string.Empty;

                    var result = DbAccess.GetFileOrderData(ID);
                    if (result != null && result.Rows.Count > 0)
                    {
                        OrderNo = Convert.ToString(result.Rows[0]["OrderNo"]);
                        PartNo  = Convert.ToString(result.Rows[0]["PartNo"]);
                    }

                    string FilePath    = ConfigurationManager.AppSettings["UploadRoot"].ToString();
                    string FilePathDoc = string.Format("{0}{1}\\{2}", FilePath, OrderNo, PartNo);
                    FilePathDoc = FilePathDoc + "\\" + GUID;
                    if (!Directory.Exists(Path.GetDirectoryName(FilePathDoc)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(FilePathDoc));
                    }

                    FileStream file = System.IO.File.Create(FilePathDoc);
                    file.Write(responseData, 0, responseData.Length);
                    file.Close();
                }
                // Send the response to client
                // if (!(path.Contains("Document") && path.Contains("MarkupBurner")))
                // {
                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.ContentType     = response.ContentType;
                context.Response.OutputStream.Write(responseData, 0, responseData.Length);
                context.Response.StatusCode = (int)response.StatusCode;
                // }
            }
            catch (Exception ex)
            { }
        }
 internal static bool ShouldCopyProxyResponseHeader(string headerName)
 {
     return(!WebHeaderCollection.IsRestricted(headerName) && StringComparer.OrdinalIgnoreCase.Compare(headerName, "set-cookie") != 0 && StringComparer.OrdinalIgnoreCase.Compare(headerName, "server") != 0 && StringComparer.OrdinalIgnoreCase.Compare(headerName, "x-powered-by") != 0 && StringComparer.OrdinalIgnoreCase.Compare(headerName, "x-aspnet-version") != 0 && 0 != StringComparer.OrdinalIgnoreCase.Compare(headerName, "www-authenticate"));
 }
Beispiel #11
0
        /// <summary>
        /// Sends the request to server.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private WebResponse SendRequestToTarget(HttpContext context)
        {
            // get the request
            var request = WebRequest.CreateDefault(RequestUrl);

            if (request == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, String.Format("The requested url, <{0}>, could not be found.", RequestUrl));
            }

            // keep the same HTTP request method
            request.Method = context.Request.HttpMethod;
            var knownVerb = KnownHttpVerb.Parse(request.Method);

            // depending on the type of this request specific values for an HTTP request
            if (request is HttpWebRequest)
            {
                var httpRequest = request as HttpWebRequest;
                httpRequest.AllowAutoRedirect = false;
                httpRequest.ServicePoint.Expect100Continue = false;

                // add all the headers from the other proxied session to this request
                foreach (string name in context.Request.Headers.AllKeys)
                {
                    // add the headers that are restricted in their supported manor
                    switch (name)
                    {
                    case "User-Agent":
                        httpRequest.UserAgent = context.Request.UserAgent;
                        break;

                    case "Connection":
                        string connection = context.Request.Headers[name];
                        if (connection.IndexOf("Keep-Alive", StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            httpRequest.KeepAlive = true;
                        }

                        var list = new List <string>();
                        foreach (string conn in connection.Split(','))
                        {
                            string c = conn.Trim();
                            if (!c.Equals("Keep-Alive", StringComparison.OrdinalIgnoreCase) && !c.Equals("Close", StringComparison.OrdinalIgnoreCase))
                            {
                                list.Add(c);
                            }
                        }

                        if (list.Count > 0)
                        {
                            httpRequest.Connection = String.Join(", ", list.ToArray());
                        }
                        break;

                    case "Transfer-Encoding":
                        httpRequest.SendChunked      = true;
                        httpRequest.TransferEncoding = context.Request.Headers[name];
                        break;

                    case "Expect":
                        httpRequest.ServicePoint.Expect100Continue = true;
                        break;

                    case "If-Modified-Since":
                        DateTime ifModifiedSince;
                        if (DateTime.TryParse(context.Request.Headers[name], out ifModifiedSince))
                        {
                            httpRequest.IfModifiedSince = ifModifiedSince;
                        }
                        break;

                    case "Content-Length":
                        httpRequest.ContentLength = context.Request.ContentLength;
                        break;

                    case "Content-Type":
                        httpRequest.ContentType = context.Request.ContentType;
                        break;

                    case "Accept":
                        httpRequest.Accept = String.Join(", ", context.Request.AcceptTypes);
                        break;

                    case "Referer":
                        httpRequest.Referer = context.Request.UrlReferrer.OriginalString;
                        break;
                    }

                    // add to header if not restricted
                    if (!WebHeaderCollection.IsRestricted(name, false))
                    {
                        // it is nessisary to get the values for headers that are allowed to specifiy
                        // multiple values in an instance (i.e. Cookie)
                        string[] values = context.Request.Headers.GetValues(name);
                        foreach (string value in values)
                        {
                            request.Headers.Add(name, value);
                        }
                    }
                }
            }

            // add the vanity url to the header
            if (Manager.Configuration.Rewriter.AllowVanityHeader)
            {
                request.Headers.Add("X-Reverse-Proxied-By", Manager.RewriterUserAgent);
                request.Headers.Add("X-ManagedFusion-Rewriter-Version", Manager.RewriterVersion.ToString(2));
            }

            /*
             * Add Proxy Standard Protocol Headers
             */

            // http://en.wikipedia.org/wiki/X-Forwarded-For
            request.Headers.Add("X-Forwarded-For", context.Request.UserHostAddress);

            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.45
            string currentServerName     = context.Request.ServerVariables["SERVER_NAME"];
            string currentServerPort     = context.Request.ServerVariables["SERVER_PORT"];
            string currentServerProtocol = context.Request.ServerVariables["SERVER_PROTOCOL"];

            if (currentServerProtocol.IndexOf("/") >= 0)
            {
                currentServerProtocol = currentServerProtocol.Substring(currentServerProtocol.IndexOf("/") + 1);
            }

            string currentVia = String.Format("{0} {1}:{2} ({3})", currentServerProtocol, currentServerName, currentServerPort, Manager.RewriterNameAndVersion);

            request.Headers.Add("Via", currentVia);

            /*
             * End - Add Proxy Standard Protocol Headers
             */

            OnRequestToTarget(context, request);

            // ContentLength is set to -1 if their is no data to send
            if (request.ContentLength >= 0 && !knownVerb.ContentBodyNotAllowed)
            {
                int bufferSize = Manager.Configuration.Rewriter.Proxy.RequestSize;
                using (Stream requestStream = request.GetRequestStream(), bufferStream = new BufferedStream(context.Request.InputStream, Manager.Configuration.Rewriter.Proxy.BufferSize))
                {
                    byte[] buffer = new byte[bufferSize];

                    try
                    {
                        while (true)
                        {
                            // make sure that the stream can be read from
                            if (!bufferStream.CanRead)
                            {
                                break;
                            }

                            int bytesReturned = bufferStream.Read(buffer, 0, bufferSize);

                            // if not bytes were returned the end of the stream has been reached
                            // and the loop should exit
                            if (bytesReturned == 0)
                            {
                                break;
                            }

                            // write bytes to the response
                            requestStream.Write(buffer, 0, bytesReturned);
                        }
                    }
                    catch (Exception exc)
                    {
                        Manager.Log("Error on request: " + exc.Message, "Proxy");
                    }
                }
            }

            // get the response
            WebResponse response;

            try { response = request.GetResponse(); }
            catch (WebException exc)
            {
                Manager.Log(String.Format("Error received from {0}: {1}", request.RequestUri, exc.Message), "Proxy");
                response = exc.Response;
            }

            if (response == null)
            {
                Manager.Log("No response was received, returning a '400 Bad Request' to the client.", "Proxy");
                throw new HttpException((int)HttpStatusCode.BadRequest, String.Format("The requested url, <{0}>, could not be found.", RequestUrl));
            }

            Manager.Log(response.GetType().ToString(), "Proxy");
            if (response is HttpWebResponse)
            {
                var httpResponse = response as HttpWebResponse;
                Manager.Log(String.Format("Received '{0} {1}'", ((int)httpResponse.StatusCode), httpResponse.StatusDescription), "Proxy");
            }

            return(response);
        }
 internal static bool ShouldCopyProxyRequestHeader(string headerName)
 {
     return(!WebHeaderCollection.IsRestricted(headerName) && StringComparer.OrdinalIgnoreCase.Compare(headerName, "accept-encoding") != 0 && StringComparer.OrdinalIgnoreCase.Compare(headerName, "cookie") != 0 && StringComparer.OrdinalIgnoreCase.Compare(headerName, "authorization") != 0 && 0 != StringComparer.OrdinalIgnoreCase.Compare(headerName, "proxy-authorization"));
 }
Beispiel #13
0
        //private bool IncrementRequestCount(ApplicationInstance instance)
        //{
        //    LbIncrementRequestCountRequest request = new LbIncrementRequestCountRequest(Settings.Credentials);
        //    request.ApplicationId = instance.ApplicationId;
        //    request.InstanceId = instance.Id;
        //    EndPoints.LoadBalancerWebService.IncrementRequestCount(request);
        //    return true;
        //}

        //private void DecrementRequestCount(ApplicationInstance instance)
        //{
        //    LbDecrementRequestCountRequest request = new LbDecrementRequestCountRequest(Settings.Credentials);
        //    request.ApplicationId = instance.ApplicationId;
        //    request.InstanceId = instance.Id;
        //    EndPoints.LoadBalancerWebService.DecrementRequestCount(request);
        //}

        /// <summary>
        /// Sends the request to server
        /// Implemented using Managed Fusion URL Rewriter
        /// Reference: http://www.managedfusion.com/products/url-rewriter/
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private WebResponse SendRequestToTarget(HttpContext context, Uri requestUrl, ReverseProxyContext rpContext, out bool incremented)
        {
            incremented = false;
            // get the request
            WebRequest request = WebRequest.CreateDefault(requestUrl);

            if (request == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "The requested url, <" + requestUrl + ">, could not be found.");
            }

            // keep the same HTTP request method
            request.Method = context.Request.HttpMethod;
            var knownVerb = KnownHttpVerb.Parse(request.Method);

            // depending on the type of this request specific values for an HTTP request
            if (request is HttpWebRequest)
            {
                var httpRequest = request as HttpWebRequest;
                httpRequest.AllowAutoRedirect = false;
                httpRequest.ServicePoint.Expect100Continue = false;

                // add all the headers from the other proxied session to this request
                foreach (string name in context.Request.Headers.AllKeys)
                {
                    // add the headers that are restricted in their supported manor
                    switch (name)
                    {
                    case "User-Agent":
                        httpRequest.UserAgent = context.Request.UserAgent;
                        break;

                    case "Connection":
                        string connection = context.Request.Headers[name];
                        if (connection.IndexOf("Keep-Alive", StringComparison.OrdinalIgnoreCase) > 0)
                        {
                            httpRequest.KeepAlive = true;
                        }

                        List <string> list = new List <string>();
                        foreach (string conn in connection.Split(','))
                        {
                            string c = conn.Trim();
                            if (!c.Equals("Keep-Alive", StringComparison.OrdinalIgnoreCase) && !c.Equals("Close", StringComparison.OrdinalIgnoreCase))
                            {
                                list.Add(c);
                            }
                        }

                        if (list.Count > 0)
                        {
                            httpRequest.Connection = String.Join(", ", list.ToArray());
                        }
                        break;

                    case "Transfer-Encoding":
                        httpRequest.SendChunked      = true;
                        httpRequest.TransferEncoding = context.Request.Headers[name];
                        break;

                    case "Expect":
                        httpRequest.ServicePoint.Expect100Continue = true;
                        break;

                    case "If-Modified-Since":
                        DateTime ifModifiedSince;
                        if (DateTime.TryParse(context.Request.Headers[name], out ifModifiedSince))
                        {
                            httpRequest.IfModifiedSince = ifModifiedSince;
                        }
                        break;

                    case "Content-Length":
                        httpRequest.ContentLength = context.Request.ContentLength;
                        break;

                    case "Content-Type":
                        httpRequest.ContentType = context.Request.ContentType;
                        break;

                    case "Accept":
                        httpRequest.Accept = String.Join(", ", context.Request.AcceptTypes);
                        break;

                    case "Referer":
                        httpRequest.Referer = context.Request.UrlReferrer.OriginalString;
                        break;
                    }

                    // add to header if not restricted
                    if (!WebHeaderCollection.IsRestricted(name, false))
                    {
                        // it is nessisary to get the values for headers that are allowed to specifiy
                        // multiple values in an instance (i.e. Cookie)
                        string[] values = context.Request.Headers.GetValues(name);
                        foreach (string value in values)
                        {
                            request.Headers.Add(name, value);
                        }
                    }
                }
            }

            // Add Proxy Standard Protocol Headers
            // http://en.wikipedia.org/wiki/X-Forwarded-For
            request.Headers.Add("X-Forwarded-For", context.Request.UserHostAddress);
            // Add Server Variables
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.45
            string currentServerName     = context.Request.ServerVariables["SERVER_NAME"];
            string currentServerPort     = context.Request.ServerVariables["SERVER_PORT"];
            string currentServerProtocol = context.Request.ServerVariables["SERVER_PROTOCOL"];

            if (currentServerProtocol.IndexOf("/") >= 0)
            {
                currentServerProtocol = currentServerProtocol.Substring(currentServerProtocol.IndexOf("/") + 1);
            }

            string currentVia = String.Format("{0} {1}:{2} ({3})", currentServerProtocol, currentServerName, currentServerPort, "Monoscape.LoadBalancerController");

            request.Headers.Add("Via", currentVia);

            //
            // ContentLength is set to -1 if their is no data to send
            if ((request.ContentLength >= 0) && (!knownVerb.ContentBodyNotAllowed))
            {
                int bufferSize = 64 * 1024;
                using (Stream requestStream = request.GetRequestStream(), bufferStream = new BufferedStream(context.Request.InputStream, bufferSize))
                {
                    byte[] buffer = new byte[bufferSize];

                    try
                    {
                        while (true)
                        {
                            // make sure that the stream can be read from
                            if (!bufferStream.CanRead)
                            {
                                break;
                            }
                            int bytesReturned = bufferStream.Read(buffer, 0, bufferSize);
                            // if not bytes were returned the end of the stream has been reached
                            // and the loop should exit
                            if (bytesReturned == 0)
                            {
                                break;
                            }
                            // write bytes to the response
                            requestStream.Write(buffer, 0, bytesReturned);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(typeof(ProxyHandler), "", e);
                    }
                }
            }

            WebResponse response;

            try
            {
                // Increment application instance request count
                //incremented = IncrementRequestCount(rpContext.ApplicationInstance);
                if (addReqResult != null)
                {
                    int requestId = rpContext.AddReqCaller.EndInvoke(addReqResult);
                    // Remove request from load balancer request queue
                    ASyncRemoveRequestFromQueue caller = new ASyncRemoveRequestFromQueue(RemoveRequestFromQueue);
                    caller.BeginInvoke(requestId, null, null);
                }
                // Send request to the proxy target
                response = request.GetResponse();
            }
            catch (WebException e)
            {
                Log.Error(typeof(ProxyHandler), "Error received from " + request.RequestUri + ": " + e.Message, e);
                response = e.Response;
            }

            if (response == null)
            {
                Log.Error(typeof(ProxyHandler), "The requested url " + requestUrl + " could not be found.");
                throw new HttpException((int)HttpStatusCode.NotFound, "The requested url could not be found.");
            }

            Log.Info(typeof(ProxyHandler), response.GetType().ToString());
            if (response is HttpWebResponse)
            {
                HttpWebResponse httpResponse = response as HttpWebResponse;
                Log.Info(typeof(ProxyHandler), "Received '" + ((int)httpResponse.StatusCode) + " " + httpResponse.StatusDescription + "'");
            }
            return(response);
        }
        /// <summary>
        /// Processes a message
        /// </summary>
        /// <param name="stream">The message being processed.</param>
        /// <param name="ctx">The context associated with the message.</param>
        /// <returns>The handling status for this operation.</returns>
        protected override ChainResult OnProcessInputMessage(ref WsMessage msg, BindingContext ctx)
        {
            byte[] soapResponse         = null;
            WebHeaderCollection headers = null;

            if (ctx is ClientBindingContext)
            {
                HttpWebRequest request = ctx.ContextObject as HttpWebRequest;

                if (request == null)
                {
                    msg = null;
                    return(ChainResult.Abort);
                }

                HttpWebResponse resp = request.GetResponse() as HttpWebResponse;

                if (resp == null)
                {
                    throw new WebException("", WebExceptionStatus.ReceiveFailure); // No response was received on the HTTP channel
                }

                try
                {
                    headers = (System.Net.WebHeaderCollection)resp.Headers;

                    if (resp.ProtocolVersion != HttpVersion.Version11)
                    {
                        throw new IOException(); // Invalid http version in response line.
                    }

                    if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.Accepted)
                    {
                        if (resp.ContentType.IndexOf("application/soap+xml") == -1)
                        {
                            throw new IOException(); // Bad status code in response
                        }
                    }

                    if (resp.ContentLength > 0)
                    {
                        // Return the soap response.
                        soapResponse = new byte[(int)resp.ContentLength];
                        Stream respStream = resp.GetResponseStream();

                        respStream.ReadTimeout = (int)(ctx.ReceiveTimeout.Ticks / TimeSpan.TicksPerMillisecond);

                        // Now need to read all data. We read in the loop until resp.ContentLength or zero bytes read.
                        // Zero bytes read means there was error on server and it did not send all data.
                        int respLength = (int)resp.ContentLength;
                        for (int totalBytesRead = 0; totalBytesRead < respLength;)
                        {
                            int bytesRead = respStream.Read(soapResponse, totalBytesRead, (int)resp.ContentLength - totalBytesRead);
                            // If nothing is read - means server closed connection or timeout. In this case no retry.
                            if (bytesRead == 0)
                            {
                                break;
                            }

                            // Adds number of bytes read on this iteration.
                            totalBytesRead += bytesRead;
                        }

                        headers = resp.Headers;
                    }
                    //
                    // ContentLenght == 0 is OK
                    //
                    else if (resp.ContentLength < 0)
                    {
                        throw new ProtocolViolationException(); // Invalid http header, content lenght < 0
                    }
                }
                finally
                {
                    resp.Dispose();
                    request.Dispose();
                    ctx.ContextObject = null;
                }
            }
            else // server waits for messages
            {
                HttpListenerContext listenerContext;

                try
                {
                    if (m_persistConn && ctx.ContextObject != null)
                    {
                        listenerContext = (HttpListenerContext)ctx.ContextObject;

                        listenerContext.Reset();
                    }
                    else
                    {
                        if (m_httpListener == null)
                        {
                            msg = null;
                            return(ChainResult.Abort);
                        }

                        listenerContext = m_httpListener.GetContext();
                    }

                    if (listenerContext == null)
                    {
                        msg = null;
                        return(ChainResult.Abort);
                    }

                    ctx.ContextObject = listenerContext;

                    // The context returned by m_httpListener.GetContext(); can be null in case the service was stopped.
                    HttpListenerRequest listenerRequest = listenerContext.Request;

                    HttpListenerResponse listenerResponse = listenerContext.Response;

                    listenerRequest.InputStream.ReadTimeout    = (int)(ctx.ReceiveTimeout.Ticks / TimeSpan.TicksPerMillisecond);
                    listenerResponse.OutputStream.WriteTimeout = (int)(ctx.SendTimeout.Ticks / TimeSpan.TicksPerMillisecond);

                    headers = (System.Net.WebHeaderCollection)listenerRequest.Headers;

                    System.Ext.Console.Write("Request From: " + listenerRequest.RemoteEndPoint.ToString());

                    // Checks and process headers important for DPWS
                    if (!ProcessKnownHeaders(listenerContext))
                    {
                        msg = null;
                        return(ChainResult.Abort);
                    }

                    soapResponse = null;

                    int messageLength = (int)listenerRequest.ContentLength64;
                    if (messageLength > 0)
                    {
                        // If there is content length for the message, we read it complete.
                        soapResponse = new byte[messageLength];

                        for (int offset = 0; offset < messageLength;)
                        {
                            int noRead = listenerRequest.InputStream.Read(soapResponse, offset, messageLength - offset);
                            if (noRead == 0)
                            {
                                throw new IOException("Http server got only " + offset + " bytes. Expected to read " + messageLength + " bytes.");
                            }

                            offset += noRead;
                        }
                    }
                    else
                    {
                        // In this case the message is chunk encoded, but m_httpRequest.InputStream actually does processing.
                        // So we we read until zero bytes are read.
                        bool readComplete = false;
                        int  bufferSize   = ReadPayload;
                        soapResponse = new byte[bufferSize];
                        int offset = 0;
                        while (!readComplete)
                        {
                            while (offset < ReadPayload)
                            {
                                int noRead = listenerRequest.InputStream.Read(soapResponse, offset, messageLength - offset);
                                // If we read zero bytes - means this is end of message. This is how InputStream.Read for chunked encoded data.
                                if (noRead == 0)
                                {
                                    readComplete = true;
                                    break;
                                }

                                offset += noRead;
                            }

                            // If read was not complete - increase the buffer.
                            if (!readComplete)
                            {
                                bufferSize += ReadPayload;
                                byte[] newMessageBuf = new byte[bufferSize];
                                Array.Copy(soapResponse, newMessageBuf, offset);
                                soapResponse = newMessageBuf;
                            }
                        }
                    }
                }
                catch
                {
                    ctx.ContextObject = null;
                    throw;
                }
            }

            if (headers != null)
            {
                string [] keys = headers.AllKeys;
                int       len  = keys.Length;

                ArrayList props = ctx.BindingProperties;

                for (int i = 0; i < len; i++)
                {
                    string key = keys[i];

                    if (!WebHeaderCollection.IsRestricted(key))
                    {
                        props.Add(new BindingProperty("header", key, headers[key]));
                    }
                }
            }

            System.Ext.Console.Write(soapResponse);


            msg.Body = soapResponse;

            return(ChainResult.Continue);
        }
Beispiel #15
0
        protected override async Task ProcessRequestCoreAsync(HttpContext ctx, string viewer, string world, long startTime)
        {
            var req  = ctx.Request;
            var resp = ctx.Response;

            if (req.ContentLength > 4096)
            {
                resp.StatusCode = 413;
                return;
            }

            HttpWebRequest hwr = WebRequest.CreateHttp(world + req.Url.PathAndQuery.Substring(1));

            if (req.Headers["Referer"] != null)
            {
                var hdrLine = req.Headers["Referer"];
                var schema  = hdrLine.IndexOf("//") + 2;
                var kcsUrl  = hdrLine.IndexOf("/kcs", schema);
                if (kcsUrl > 0)
                {
                    hwr.Referer = world + hdrLine.Substring(kcsUrl + 1);
                }
            }

            var proxyResponse = await Utils.Misc.ForwardRequest(req, hwr);

            if (proxyResponse == null)
            {
                resp.StatusCode = 502;
                return;
            }
            using (proxyResponse) {
                resp.StatusCode = (int)proxyResponse.StatusCode;
                foreach (var hdr in proxyResponse.Headers.AllKeys)
                {
                    switch (hdr)
                    {
                    case "Server":
                    case "Connection":
                    case "Accept-Ranges":
                    case "Content-Length":
                    case "Transfer-Encoding":
                    case "WWW-Authenticate":
                        break;

                    case "Content-Type":
                        resp.ContentType = proxyResponse.ContentType;
                        break;

                    case "Cache-Control":
                    {
                        var cacheControl = CacheControlHeaderValue.Parse(proxyResponse.Headers[hdr]);
                        if (cacheControl.Public)
                        {
                            resp.Cache.SetCacheability(HttpCacheability.Public);
                        }
                        if (cacheControl.NoCache)
                        {
                            resp.Cache.SetCacheability(HttpCacheability.NoCache);
                        }
                        if (cacheControl.MaxAge != null)
                        {
                            resp.Cache.SetMaxAge(cacheControl.MaxAge.Value);
                        }
                    }
                    break;

                    default:
                        if (WebHeaderCollection.IsRestricted(hdr, true))
                        {
                            ctx.Response.StatusCode = 501;
                            return;
                        }
                        resp.Headers[hdr] = proxyResponse.Headers[hdr];
                        break;
                    }
                }
                if (proxyResponse.ContentLength != 0)
                {
                    using (var proxyStream = proxyResponse.GetResponseStream()) {
                        await proxyStream.CopyToAsync(resp.OutputStream);
                    }
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// Sends an Http Web Request.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="contentArray">The request content.</param>
        /// <returns></returns>
        private async Task SendHttpWebRequest(HttpRequestMessage request)
        {
            HttpWebRequest client = (HttpWebRequest)WebRequest.Create(request.RequestUri.AbsoluteUri);

            client.Method      = request.Method.ToString();
            client.Timeout     = RequestTimeout;
            client.KeepAlive   = true;
            client.ContentType = ContentType;

            HttpRequestHeaders headers = request.Headers;

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    if (!WebHeaderCollection.IsRestricted(header.Key) && header.Value != null && header.Value.Count() != 0)
                    {
                        client.Headers.Add(header.Key, header.Value.FirstOrDefault());
                    }
                }
            }

#if !UNITY_WSA
            ServicePointManager.ServerCertificateValidationCallback = LightBuzzCertificateValidation.CertificateValidationCallback;
#endif

            string contentArray = request.Content != null ? await request.Content.ReadAsStringAsync() : null;

            if (contentArray != null)
            {
                using (StreamWriter streamWriter = new StreamWriter(client.GetRequestStream()))
                {
                    streamWriter.Write(contentArray);
                }
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)client.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string data = reader.ReadToEnd();

                        _result.StatusCode   = response.StatusCode;
                        _result.ReasonPhrase = _result.StatusCode.ToString();
                        _result.Content      = new StringContent(data, Encoding, ContentType);
                    }
                }
            }
            catch (WebException webException)
            {
                if (webException.Response == null)
                {
                    throw webException;
                }
                using (HttpWebResponse response = (HttpWebResponse)webException.Response)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string data = reader.ReadToEnd();

                        _result.StatusCode   = response.StatusCode;
                        _result.ReasonPhrase = _result.StatusCode.ToString();
                        _result.Content      = new StringContent(data, Encoding, ContentType);
                    }
                }
            }
        }
Beispiel #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var remoteUrl = Request.QueryString["url"];

        var req = (HttpWebRequest)WebRequest.Create(remoteUrl);

        req.AllowAutoRedirect      = false;
        req.Method                 = Request.HttpMethod;
        req.ContentType            = Request.ContentType;
        req.UserAgent              = Request.UserAgent;
        req.PreAuthenticate        = true;
        req.Headers["Remote-User"] = HttpContext.Current.User.Identity.Name;
        foreach (string each in Request.Headers)
        {
            if (!WebHeaderCollection.IsRestricted(each) && each != "Remote-User")
            {
                req.Headers.Add(each, Request.Headers.Get(each));
            }
        }
        if (Request.HttpMethod == "POST")
        {
            var outputStream = req.GetRequestStream();
            CopyStream(Request.InputStream, outputStream);
            outputStream.Close();
        }

        HttpWebResponse response;

        try
        {
            response = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException we)
        {
            response = (HttpWebResponse)we.Response;
            if (response == null)
            {
                Response.StatusCode = 13;
                Response.Write("Could not contact back-end site");
                Response.End();
                return;
            }
        }

        Response.StatusCode        = (int)response.StatusCode;
        Response.StatusDescription = response.StatusDescription;
        Response.ContentType       = response.ContentType;
        if (response.Headers.Get("Location") != null)
        {
            var urlSuffix = response.Headers.Get("Location");
            //if (urlSuffix.ToLower().StartsWith(ConfigurationSettings.AppSettings["ProxyUrl"].ToLower()))
            //    urlSuffix = urlSuffix.Substring(ConfigurationSettings.AppSettings["ProxyUrl"].Length);
            Response.AddHeader("Location", Request.Url.GetLeftPart(UriPartial.Authority) + urlSuffix);
        }
        foreach (string each in response.Headers)
        {
            if (each != "Location" && !WebHeaderCollection.IsRestricted(each))
            {
                Response.AddHeader(each, response.Headers.Get(each));
            }
        }

        CopyStream(response.GetResponseStream(), Response.OutputStream);
        response.Close();
        Response.End();
    }
        internal static void AddHeaders2(WWWRequestData requestData, IDictionary <string, string> headersToAdd)
        {
            var headers = requestData.Headers;

            foreach (var kvp in headersToAdd)
            {
                if (WebHeaderCollection.IsRestricted(kvp.Key) || string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.Equals(kvp.Key, "Accept", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Accept", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "Connection", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Connection", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Content-Type", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Content-Length", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "Expect", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Expect", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "Date", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Date", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
                    {
                        #if !UNITY_WEBPLAYER
                        headers.Add("User-Agent", kvp.Value);
                        #endif
                    }
                    else if (string.Equals(kvp.Key, "Host", StringComparison.OrdinalIgnoreCase))
                    {
                        #if !UNITY_WEBPLAYER
                        headers.Add("Host", kvp.Value);
                        #endif
                    }
                    else if (string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("Range", kvp.Value);
                    }
                    else if (string.Equals(kvp.Key, "If-Modified-Since", StringComparison.OrdinalIgnoreCase))
                    {
                        headers.Add("If-Modified-Since", kvp.Value);
                    }
                    else
                    {
                        throw new NotSupportedException("Header with name " + kvp.Key + " is not supported");
                    }
                }
                else
                {
                    headers.Add(kvp.Key, kvp.Value);
                }
            }
        }
Beispiel #19
0
        public static async Task <HttpWebResponse> ForwardRequest(HttpRequest req, string uri, string referer = null)
        {
            var hwr = CreateRequest(uri);

            hwr.Method = req.HttpMethod;
            if (referer != null)
            {
                hwr.Referer = referer;
            }

            foreach (var hdr in req.Headers.AllKeys)
            {
                switch (hdr)
                {
                case "Accept":
                    hwr.Accept = req.Headers[hdr];
                    break;

                case "Content-Type":
                    hwr.ContentType = req.ContentType;
                    break;

                case "Content-Length":
                case "User-Agent":     // Forging UA
                case "Connection":     // Keep alive anyway
                case "Host":
                case "Proxy-Connection":
                case "Range":
                case "Date":
                case "Cookie":
                case "Transfer-Encoding":
                case "Accept-Encoding":
                case "Referer":
                    break;     //Ignore these.

                case "Expect":
                    return(null);

                case "If-Modified-Since":
                {
                    var hdrLine   = req.Headers[hdr];
                    var semicolon = hdrLine.IndexOf(';');
                    if (semicolon < 0)
                    {
                        semicolon = hdrLine.Length;
                    }
                    hdrLine             = hdrLine.Substring(0, semicolon);
                    hwr.IfModifiedSince = DateTime.Parse(hdrLine);
                }
                break;

                default:
                    if (WebHeaderCollection.IsRestricted(hdr, false))
                    {
                        return(null);
                    }
                    hwr.Headers[hdr] = req.Headers[hdr];
                    break;
                }
            }

            if (req.HttpMethod != "GET" && req.HttpMethod != "HEAD" && req.ContentLength != 0)
            {
                req.InputStream.Position = 0;
                using (var outGoingStream = await hwr.GetRequestStreamAsync())
                    await req.InputStream.CopyToAsync(outGoingStream);
            }

            try {
                return((HttpWebResponse)await hwr.GetResponseAsync());
            } catch (WebException e) {
                return((HttpWebResponse)e.Response);
            }
        }
Beispiel #20
0
        public void ProcessRequest(HttpContext context)
        {
            // Create the web request to communicate with the back-end site
            string remoteUrl = ConfigurationManager.AppSettings["ProxyUrl"] +
                               context.Request.Path;

            if (context.Request.QueryString.ToString() != "")
            {
                remoteUrl += "?" + context.Request.QueryString;
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteUrl);

            request.AllowAutoRedirect = false;
            request.Method            = context.Request.HttpMethod;
            request.ContentType       = context.Request.ContentType;
            request.UserAgent         = context.Request.UserAgent;
            string basicPwd = ConfigurationManager.AppSettings.Get("basicPwd");

            request.Credentials = basicPwd == null ?
                                  CredentialCache.DefaultCredentials :
                                  new NetworkCredential(HttpContext.Current.User.Identity.Name, basicPwd);
            request.PreAuthenticate = true;
            // The Remote-User header is non-ideal; included for compatibility
            request.Headers["Remote-User"] = HttpContext.Current.User.Identity.Name;
            foreach (String each in context.Request.Headers)
            {
                if (!WebHeaderCollection.IsRestricted(each) && each != "Remote-User")
                {
                    request.Headers.Add(each, context.Request.Headers.Get(each));
                }
            }
            if (context.Request.HttpMethod == "POST")
            {
                Stream outputStream = request.GetRequestStream();
                CopyStream(context.Request.InputStream, outputStream);
                outputStream.Close();
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (System.Net.WebException we)
            {
                response = (HttpWebResponse)we.Response;
                if (response == null)
                {
                    context.Response.StatusCode = 13;
                    context.Response.Write("Could not contact back-end site");
                    context.Response.End();
                    return;
                }
            }

            // Copy response from server back to client
            context.Response.StatusCode        = (int)response.StatusCode;
            context.Response.StatusDescription = response.StatusDescription;
            context.Response.ContentType       = response.ContentType;
            if (response.Headers.Get("Location") != null)
            {
                if (ConfigurationManager.AppSettings.Get("traceRedirect") != null)
                {
                    event_log.WriteEntry("Back-end redirecting to: " + response.Headers.Get("Location"), EventLogEntryType.Information);
                }
                string urlSuffix = response.Headers.Get("Location");
                if (urlSuffix.ToLower().StartsWith(ConfigurationManager.AppSettings["ProxyUrl"].ToLower()))
                {
                    urlSuffix = urlSuffix.Substring(ConfigurationManager.AppSettings["ProxyUrl"].Length);
                }
                context.Response.AddHeader("Location", context.Request.Url.GetLeftPart(UriPartial.Authority) + urlSuffix);
            }
            foreach (String each in response.Headers)
            {
                if (each != "Location" && !WebHeaderCollection.IsRestricted(each))
                {
                    context.Response.AddHeader(each, response.Headers.Get(each));
                }
            }
            CopyStream(response.GetResponseStream(), context.Response.OutputStream);
            response.Close();
            context.Response.End();
        }
        public void ProcessRequest(HttpContext context)
        {
            string requestUrl = context.Request.Url.AbsoluteUri;
            string remoteUrl  = Regex.Replace(requestUrl, ".*AWLServiceProxyHandler.ashx", EndpointUrl);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteUrl);

            request.AllowAutoRedirect = false;
            request.Method            = context.Request.HttpMethod;
            request.Credentials       = CredentialCache.DefaultCredentials;
            request.ContentType       = context.Request.ContentType;
            request.UserAgent         = context.Request.UserAgent;
            request.PreAuthenticate   = true;
            foreach (string each in context.Request.Headers)
            {
                if (!WebHeaderCollection.IsRestricted(each) && each != "Remote-User")
                {
                    request.Headers.Add(each, context.Request.Headers.Get(each));
                }
            }
            request.Headers.Add("X-ServerIdentifier", ConfigurationManager.AppSettings["ServerID"]);
            if (context.Request.HttpMethod == "POST")
            {
                Stream outputStream = request.GetRequestStream();
                CopyStream(context.Request.InputStream, outputStream);
                outputStream.Close();
            }
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException we)
            {
                response = (HttpWebResponse)we.Response;
                if (response == null)
                {
                    context.Response.StatusCode = 13;
                    context.Response.Write("Could not contact back-end site");
                    context.Response.End();
                    return;
                }
            }
            // Copy response from server back to client
            context.Response.StatusCode        = (int)response.StatusCode;
            context.Response.StatusDescription = response.StatusDescription;
            context.Response.ContentType       = response.ContentType;
            if (response.Headers.Get("Location") != null)
            {
                string urlSuffix = response.Headers.Get("Location");
                if (urlSuffix.ToLower().StartsWith(remoteUrl.ToLower()))
                {
                    urlSuffix = urlSuffix.Substring(remoteUrl.Length);
                }
                context.Response.AddHeader("Location", context.Request.Url.GetLeftPart(UriPartial.Authority) + urlSuffix);
            }
            foreach (string each in response.Headers)
            {
                if (each != "Location" && !WebHeaderCollection.IsRestricted(each))
                {
                    context.Response.AddHeader(each, response.Headers.Get(each));
                }
            }
            context.Response.AddHeader("X-ServerIdentifier", ConfigurationManager.AppSettings["ServerID"]);
            CopyStream(response.GetResponseStream(), context.Response.OutputStream);
            response.Close();
            context.Response.End();

            return;
        }
Beispiel #22
0
        public MFTestResults TestWebHeaderCollectionIsRestricted()
        {
            MFTestResults result = MFTestResults.Pass;

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + Utilities.GetLocalIpAddress() + ":" + HttpServer.s_CurrentPort.ToString() + "/");  //expect 200 - OK

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            Log.Comment("Set Version 1.1");
            wr.ProtocolVersion = new Version(1, 1);

            try
            {
                WebHeaderCollection wrc = wr.Headers;

                //Attempt to add Restricted header
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Accept))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Connection))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ContentLength))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ContentType))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Date))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Expect))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Host))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.IfModifiedSince))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Range))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Referer))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.TransferEncoding))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.UserAgent))
                {
                    result = MFTestResults.Fail;
                }
                if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ProxyConnection))
                {
                    result = MFTestResults.Fail;
                }
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }

            return(result);
        }
        // As per MSDN documentation (http://msdn.microsoft.com/en-us/library/system.net.webheadercollection%28v=VS.80%29.aspx)
        // some headers are restricted, cannot be set through the request.Headers property and must be
        // set through properties on the HttpWebRequest
        internal static void AddHeaders(HttpWebRequest request, IDictionary <string, string> headersToAdd)
        {
            var headers = request.Headers;

            foreach (var kvp in headersToAdd)
            {
                if (WebHeaderCollection.IsRestricted(kvp.Key) || string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.Equals(kvp.Key, "Accept", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Accept = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "Connection", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Connection = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
                    {
                        request.ContentType = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "Expect", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Expect = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
                    {
                        request.UserAgent = kvp.Value;
                    }
                    // Date accessor is only present in .NET 4.0, so using reflection
                    else if (string.Equals(kvp.Key, "Date", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { "Date", kvp.Value });
                    }
                    // Host accessor is only present in .NET 4.0, so using reflection
                    else if (string.Equals(kvp.Key, "Host", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { "Host", kvp.Value });
                    }
                    else if (string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { "Range", kvp.Value });
                    }
                    else
                    {
                        throw new NotSupportedException("Header with name " + kvp.Key + " is not suppored");
                    }

                    /*
                     * // Content-Length is not supported because it is one of the headers known AFTER signing
                     * else if (string.Equals(kvp.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
                     *  throw new NotSupportedException();
                     * // If-Modified-Since is not supported because the required parsing methods are internal
                     * else if (string.Equals(kvp.Key, "If-Modified-Since", StringComparison.OrdinalIgnoreCase))
                     *  throw new NotSupportedException();
                     * // Range is not supported for SDK requests
                     * else if (string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                     *  throw new NotSupportedException();
                     * // Referer is not supported for SDK requests
                     * else if (string.Equals(kvp.Key, "Referer", StringComparison.OrdinalIgnoreCase))
                     *  throw new NotSupportedException();
                     * // Transfer-Encoding is not supported for SDK requests
                     * else if (string.Equals(kvp.Key, "Transfer-Encoding", StringComparison.OrdinalIgnoreCase))
                     *  throw new NotSupportedException();
                     * // Proxy-Connection is not supported, proxy must be set using config object
                     * else if (string.Equals(kvp.Key, "Proxy-Connection", StringComparison.OrdinalIgnoreCase))
                     *  throw new NotSupportedException();
                     */
                }
                else
                {
                    headers[kvp.Key] = kvp.Value;
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// HTTP(GET/POST 键值对参数列表)
        /// </summary>
        /// <returns>响应内容</returns>
        public string SendPost()
        {
            if (this.files.Count > 0)
            {
                return(HttpUploadFile(this.files.ToDictionary(k => k.Key, v => v.Value as object)));
            }

            HttpWebRequest  req       = null;
            HttpWebResponse rsp       = null;
            Stream          reqStream = null;
            Encoding        encoding  = null;

            try
            {
                if (method.ToLower() == "post")
                {
                    req                 = (HttpWebRequest)WebRequest.Create(url);
                    req.Method          = "POST";
                    req.KeepAlive       = false;
                    req.ProtocolVersion = HttpVersion.Version10;
                    req.Timeout         = Timeout;
                    //头文件
                    if (headers.Count > 0)
                    {
                        foreach (KeyValuePair <string, string> header in headers)
                        {
                            if (!WebHeaderCollection.IsRestricted(header.Key))
                            {
                                req.Headers.Add(header.Key, header.Value);
                            }
                            else
                            {
                                req.Host        = "14.17.22.55:8028";
                                req.ContentType = "application/json";
                            }
                        }
                    }
                    //证书
                    if (credentials != null)
                    {
                        req.Credentials = credentials;
                    }

                    req.CookieContainer = CurrentCookie ?? (CurrentCookie = new CookieContainer());
                    reqStream           = req.GetRequestStream();
                    if (parameters.Count > 0)
                    {
                        byte[] postData = null;
                        //StreamWriter myStreamWriter = new StreamWriter(reqStream, Encoding.GetEncoding("utf-8"));
                        //postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, false, Encode));
                        postData = Encoding.UTF8.GetBytes(BuildQueryTest(parameters, false, Encode));
                        reqStream.Write(postData, 0, postData.Length);
                    }
                    else
                    {
                        byte[] postData = Encoding.GetEncoding(Encode).GetBytes(url);
                        reqStream.Write(postData, 0, postData.Length);
                    }
                }
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });
                try
                {
                    rsp = (HttpWebResponse)req.GetResponse();
                }
                catch (WebException ex)
                {
                    var rs = ex.Response.GetResponseStream();
                    var sr = new StreamReader(rs, System.Text.Encoding.UTF8);

                    var Error = sr.ReadToEnd();
                    rs.Close();
                    sr.Close();

                    Debug.Write(ex.Message);                                                       //远程服务器返回错误: (400) 错误的请求。
                    var strResponse = GetResponseAsString((HttpWebResponse)ex.Response, encoding); //这样获取web服务器返回数据
                }
                if (CurrentCookie.Count == 0)
                {
                    CurrentCookie.Add(rsp.Cookies);
                }

                encoding = Encoding.GetEncoding(rsp.CharacterSet ?? Encode);
                return(GetResponseAsString(rsp, encoding));
            }
            finally
            {
                if (reqStream != null)
                {
                    reqStream.Close();
                }
                if (rsp != null)
                {
                    rsp.Close();
                }
            }
        }
Beispiel #25
0
        HttpWebRequest setRequest(HttpWebRequest request, bool Post, string host, string body, string referUrl = null, bool AllowRedirect = false, CookieContainer cc = null, string contentType = null)
        {
#if !DEBUG
            //request.Proxy = null;
#endif
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.Headers.Add("Accept-Encoding", "gzip,deflate,br");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
            request.CookieContainer   = cc;
            request.AllowAutoRedirect = AllowRedirect;
            request.Host = host;
            request.ServicePoint.Expect100Continue = false;
            request.Referer = referUrl;
            request.Timeout = 35000;
            if (contentType != null)
            {
                request.ContentType = contentType;
            }
            request.Method = WebRequestMethods.Http.Connect;
            if (Post)
            {
                request.Method = "POST";
                if (body != null)
                {
                    StreamWriter sw = new StreamWriter(request.GetRequestStream());
                    sw.Write(body);
                    sw.Flush();
                    sw.Close();
                }
            }
            else
            {
                request.Method        = "GET";
                request.ContentLength = 0;
            }
            //if (!string.IsNullOrEmpty(referUrl))
            //{
            //    request.Headers.Add("Origin", Referer);
            //}
            return(request);

            HttpWebRequest req = null;

            /*
             *
             *
             * req.AllowAutoRedirect = AllowRedirect;
             * req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
             * req.ProtocolVersion = HttpVersion.Version10;
             * //bool useCookie = req.SupportsCookieContainer;
             * req.CookieContainer = new CookieContainer();
             * if (cc != null)
             *  req.CookieContainer.Add(cc);
             * //useCookie = req.SupportsCookieContainer;
             * req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8";
             * req.Host = host.Replace("https://", "").Replace("http://", "");
             * if (!string.IsNullOrEmpty(referUrl))
             *  req.Referer = referUrl;
             * req.UserAgent = DefaultUserAgent;
             * req.KeepAlive = true;
             * req.ServicePoint.Expect100Continue = false;
             * req.Headers.Add("Accept-Encoding", "gzip,deflate");
             * req.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,en;q=0.5,de-de;q=0.3");
             */
            /*
             * request.KeepAlive = true;
             * request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
             * request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
             * request.Headers.Add("Accept-Encoding", "gzip,deflate,br");
             * request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
             * request.CookieContainer = cookieContainer;
             * request.AllowAutoRedirect = false;
             * request.ServicePoint.Expect100Continue = false;
             * request.Referer = Referer;
             * request.Timeout = 35000;
             *
             *
             */


            //req.Headers.Add("Host", host.Replace("https://", "").Replace("http://", ""));
            //req.Headers.Add("DNT", "1");
            if (WebHeaderCollection.IsRestricted("Host"))
            {
                //req.Headers.Set(HttpRequestHeader.Host, host.Replace("https://", "").Replace("http://", ""));
                SetHeaderValue(req.Headers, "Host", host.Replace("https://", "").Replace("http://", ""));
            }

            req.Headers.Add("Upgrade-Insecure-Requests", "1");

            //req.Method = Post ? "Post" : "GET";
            if (cc != null)
            {
                //if (cc.Count>0 && cc[cc.Count-1].Name != "ai_user")
                //{
                //    string ai_user = string.Format("n3YUx |{0}", DateTime.UtcNow.ToString("yyyy MM ddThh:mm:ss.000"));
                //    cc.Add(new Cookie("ai_user", ai_user, "/", req.Host));
                //}
                List <string> cs = new List <string>();

                //req.CookieContainer.Add(cc);
                string strCookie = string.Join(";", cs);
                SetHeaderValue(req.Headers, "Cookie", strCookie);
            }
        }
Beispiel #26
0
        public static void CopyHeaders(HttpWebRequest src, HttpWebRequest dest)
        {
            foreach (string header in src.Headers)
            {
                var values = src.Headers.GetValues(header);
                if (values == null)
                {
                    continue;
                }
                if (WebHeaderCollection.IsRestricted(header))
                {
                    switch (header)
                    {
                    case "Accept":
                        dest.Accept = src.Accept;
                        break;

                    case "Connection":
                        // explicitly ignoring this
                        break;

                    case "Content-Length":
                        break;

                    case "Content-Type":
                        dest.ContentType = src.ContentType;
                        break;

                    case "Date":
                        break;

                    case "Expect":
                        // explicitly ignoring this
                        break;

#if !NET_3_5
                    case "Host":
                        dest.Host = src.Host;
                        break;
#endif
                    case "If-Modified-Since":
                        dest.IfModifiedSince = src.IfModifiedSince;
                        break;

                    case "Range":
                        throw new NotSupportedException("Range copying isn't supported at this stage, we don't support range queries anyway, so it shouldn't matter");

                    case "Referer":
                        dest.Referer = src.Referer;
                        break;

                    case "Transfer-Encoding":
                        dest.SendChunked = src.SendChunked;

                        break;

                    case "User-Agent":
                        dest.UserAgent = src.UserAgent;
                        break;

                    case "Proxy-Connection":
                        dest.Proxy = src.Proxy;
                        break;

                    default:
                        throw new ArgumentException(string.Format("No idea how to handle restricted header: '{0}'", header));
                    }
                }
                else
                {
                    foreach (var value in values)
                    {
                        dest.Headers.Add(header, value);
                    }
                }
            }
        }
        // As per MSDN documentation (http://msdn.microsoft.com/en-us/library/system.net.webheadercollection%28v=VS.80%29.aspx)
        // some headers are restricted, cannot be set through the request.Headers property and must be
        // set through properties on the HttpWebRequest
        internal static void AddHeaders(HttpWebRequest request, IDictionary <string, string> headersToAdd)
        {
            var headers = request.Headers;

            foreach (var kvp in headersToAdd)
            {
                if (WebHeaderCollection.IsRestricted(kvp.Key) || string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.Equals(kvp.Key, "Accept", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Accept = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "Connection", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Connection = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
                    {
                        request.ContentType = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
                    {
                        request.ContentLength = long.Parse(kvp.Value, CultureInfo.InvariantCulture);
                    }
                    else if (string.Equals(kvp.Key, "Expect", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Expect = kvp.Value;
                    }
                    else if (string.Equals(kvp.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
                    {
                        request.UserAgent = kvp.Value;
                    }
                    // Date accessor is only present in .NET 4.0, so using reflection
                    else if (string.Equals(kvp.Key, "Date", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { "Date", kvp.Value });
                    }
                    // Host accessor is only present in .NET 4.0, so using reflection
                    else if (string.Equals(kvp.Key, "Host", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { "Host", kvp.Value });
                    }
                    else if (string.Equals(kvp.Key, "Range", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { "Range", kvp.Value });
                    }
                    else if (string.Equals(kvp.Key, "If-Modified-Since", StringComparison.OrdinalIgnoreCase))
                    {
                        _addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { kvp.Key, kvp.Value });
                    }
                    else
                    {
                        throw new NotSupportedException("Header with name " + kvp.Key + " is not suppored");
                    }
                }
                else
                {
                    headers[kvp.Key] = kvp.Value;
                }
            }
        }
Beispiel #28
0
 public void HttpRequestHeader_IsRestricted_Success()
 {
     Assert.True(WebHeaderCollection.IsRestricted("Accept"));
     Assert.False(WebHeaderCollection.IsRestricted("Age"));
     Assert.False(WebHeaderCollection.IsRestricted("Accept", true));
 }
Beispiel #29
0
        private void WriteMetadata(RavenJObject metadata)
        {
            if (metadata == null || metadata.Count == 0)
            {
                return;
            }

            foreach (var prop in metadata)
            {
                if (prop.Value == null)
                {
                    continue;
                }

                if (prop.Value.Type == JTokenType.Object ||
                    prop.Value.Type == JTokenType.Array)
                {
                    continue;
                }

                var headerName = prop.Key;
                var value      = prop.Value.Value <object>().ToString();
                if (headerName == Constants.MetadataEtagField)
                {
                    headerName = "If-None-Match";
                    if (!value.StartsWith("\""))
                    {
                        value = "\"" + value;
                    }
                    if (!value.EndsWith("\""))
                    {
                        value = value + "\"";
                    }
                }

                bool isRestricted;
                try
                {
                    isRestricted = WebHeaderCollection.IsRestricted(headerName);
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Could not figure out how to treat header: " + headerName, e);
                }
                // Restricted headers require their own special treatment, otherwise an exception will
                // be thrown.
                // See http://msdn.microsoft.com/en-us/library/78h415ay.aspx
                if (isRestricted)
                {
                    switch (headerName)
                    {
                    /*case "Date":
                     * case "Referer":
                     * case "Content-Length":
                     * case "Expect":
                     * case "Range":
                     * case "Transfer-Encoding":
                     * case "User-Agent":
                     * case "Proxy-Connection":
                     * case "Host": // Host property is not supported by 3.5
                     *  break;*/
                    case "Content-Type":
                        headers["Content-Type"] = value;
                        break;

                    case "If-Modified-Since":
                        DateTime tmp;
                        DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out tmp);
                        httpClient.DefaultRequestHeaders.IfModifiedSince = tmp;
                        break;

                    case "Accept":
                        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(value));
                        break;

                    case "Connection":
                        httpClient.DefaultRequestHeaders.Connection.Add(value);
                        break;
                    }
                }
                else
                {
                    headers[headerName] = value;
                }
            }
        }
        public ActionResult RunConsumerInfoApi(string billingPostalCode, string authKey)
        {
            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                //Create a web request for "www.msn.com".
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://api-sbox.dnlsrv.com/cigateway/id/v1/consumerInfo");
                myHttpWebRequest.Method = "POST";

                //Get the headers associated with the request.
                WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;
                if (!WebHeaderCollection.IsRestricted("Accept"))
                {
                    myWebHeaderCollection.Add("Accept", "application/json");
                }
                if (!WebHeaderCollection.IsRestricted("Content-Type"))
                {
                    myWebHeaderCollection.Add("Content-Type", "application/json");
                }
                if (!WebHeaderCollection.IsRestricted("Authorization"))
                {
                    myWebHeaderCollection.Add("Authorization", "M58Kf103FkYNgFbrrQkl2sSAO6lUBdau");
                }
                if (!WebHeaderCollection.IsRestricted("RequestTime"))
                {
                    myWebHeaderCollection.Add("RequestTime", ConfigurationManager.AppSettings["RequestTime"]);
                }

                using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
                {
                    string json = "{ \"merchantId\" : \"02180007169632\", " +
                                  "\"authenticationKey\" : \"" + authKey + "\", " +
                                  "\"intendedUseCase\" : \"AR\"," +
                                  "\"consumerAuth\" : \"" + billingPostalCode + "\"," +
                                  "\"consumerAuthType\" : \"PostalCode\"," +
                                  "\"correlationId\" : \"" + RandomString(16) + "\"" +
                                  " }";

                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseText = streamReader.ReadToEnd();

                    Object _res          = new JavaScriptSerializer().Deserialize <RootResultsObject>(responseText);
                    string key           = "e6WMHBIw94OJBoaii3+S9Q==";
                    string cipherSalt    = ((DanalJSONApp.Models.RootResultsObject)_res).results.cipherSalt.Trim();
                    string encryptedData = ((DanalJSONApp.Models.RootResultsObject)_res).results.encryptedData;

                    string decryptedData   = MyCryptoClass.AES_decrypt(encryptedData, key, MyCryptoClass.Base64Encode(cipherSalt));
                    Object consumerInfoObj = new JavaScriptSerializer().Deserialize <DanalJSONApp.Models.ConsumerInfo.RootObject>(decryptedData);
                    return(Json(consumerInfoObj, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                return(Json("fail", JsonRequestBehavior.AllowGet));
            }
        }