Example #1
0
        //public static HttpWebRequest BuildHttpWebRequest(HttpRequestBase request, string url, int timeoutInSecond)
        //{
        //    if (request == null)
        //        return null;

        //    HttpWebRequest httpReq = WebRequest.Create(url) as HttpWebRequest;
        //    if (request.IsSecureConnection)
        //    {
        //        ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
        //        httpReq.ProtocolVersion = HttpVersion.Version10;
        //    }

        //    //注意:HttpWebRequire.Method默认为Get,
        //    //在写入请求前必须把HttpWebRequire.Method设置为Post,
        //    //否则在使用BeginGetRequireStream获取请求数据流的时候,系统就会发出“无法发送具有此谓词类型的内容正文”的异常。
        //    httpReq.Method = request.HttpMethod;

        //    // Copy unrestricted headers (including cookies, if any)
        //    //foreach (string headerKey in request.Headers.AllKeys)
        //    //{
        //    //    switch (headerKey)
        //    //    {
        //    //        case "Connection":
        //    //        case "Content-Length":
        //    //        case "Date":
        //    //        case "Expect":
        //    //        case "Host":
        //    //        case "If-Modified-Since":
        //    //        case "Range":
        //    //        case "Transfer-Encoding":
        //    //        case "Proxy-Connection":
        //    //            // Let IIS handle these
        //    //            break;
        //    //        case "Accept":
        //    //        case "Content-Type":
        //    //        case "Referer":
        //    //        case "User-Agent":
        //    //        //case "Cookie":
        //    //        case "Cache-Control":
        //    //            // Restricted - copied below
        //    //            break;
        //    //        default:
        //    //            httpReq.Headers[headerKey] = request.Headers[headerKey];
        //    //            break;
        //    //    }
        //    //}
        //    httpReq.ServicePoint.Expect100Continue = false;
        //    httpReq.Timeout = timeoutInSecond * 1000;
        //    // Copy restricted headers
        //    if (!request.AcceptTypes.IsNullOrEmpty())
        //    {
        //        httpReq.Accept = string.Join(",", request.AcceptTypes);
        //    }
        //    if (request.UrlReferrer != null)
        //    {
        //        httpReq.Referer = request.UrlReferrer.AbsoluteUri;
        //    }
        //    httpReq.UserAgent = request.UserAgent;
        //    httpReq.ContentLength = request.ContentLength;
        //    httpReq.ContentType = request.ContentType;
        //    httpReq.KeepAlive = !"close".Equals(request.Headers["Connection"], StringComparison.OrdinalIgnoreCase);//keep-alive
        //    httpReq.KeepAlive = false;
        //    httpReq.Connection = httpReq.Connection;
        //    DateTime ifModifiedSince;
        //    if (DateTime.TryParse(request.Headers["If-Modified-Since"], out ifModifiedSince))
        //    {
        //        httpReq.IfModifiedSince = ifModifiedSince;
        //    }
        //    string transferEncoding = request.Headers["Transfer-Encoding"];
        //    if (transferEncoding != null)
        //    {
        //        httpReq.SendChunked = true;
        //        httpReq.TransferEncoding = transferEncoding;
        //    }

        //    // Copy content (if content body is allowed)
        //    if (request.HttpMethod != WebRequestMethods.Http.Get && request.HttpMethod != WebRequestMethods.Http.Head && request.ContentLength > 0)
        //    {
        //        using (Stream httpReqStream = httpReq.GetRequestStream())
        //        {
        //            request.InputStream.CopyTo(httpReqStream, request.ContentLength);
        //            httpReqStream.Close();
        //        }
        //    }

        //    return httpReq;
        //}

        public static HttpWebRequest BuildHttpWebRequest(string url, NameValueCollection param, RequestMethod method, int timeoutInSecond, Encoding encoding, string userAgent, CookieContainer cookies, string referer, string acceptTypes, string host, NameValueCollection headers)
        {
            encoding = encoding ?? Encoding.UTF8;
            HttpWebRequest req = null;
            string fullurl = string.Empty;
            if (method != RequestMethod.POST && param != null && param.Count > 0)
                fullurl = WebUrlHelper.AppendNVP(url, param);
            else
                fullurl = url;

            req = WebRequest.Create(fullurl) as HttpWebRequest;
            if (fullurl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
                req.ProtocolVersion = HttpVersion.Version10;
            }

            req.Method = method.ToString();
            if (timeoutInSecond > 99)
            {
                req.Timeout = timeoutInSecond;
            }
            else
            {
                req.Timeout = timeoutInSecond * 1000;
            }
            req.ReadWriteTimeout = req.Timeout;
            req.ServicePoint.Expect100Continue = false;
            if (!string.IsNullOrEmpty(host))
                req.Host = host;
            if (!string.IsNullOrEmpty(userAgent))
                req.UserAgent = userAgent;
            if (cookies != null)
                req.CookieContainer = cookies;
            if (!string.IsNullOrEmpty(referer))
                req.Referer = referer;
            if (!string.IsNullOrEmpty(acceptTypes))
                req.Accept = acceptTypes;
            if (!headers.IsNullOrEmpty())
                req.Headers.Add(headers);
            if (method == RequestMethod.POST || method == RequestMethod.PUT)
            {
                req.ContentType = "application/x-www-form-urlencoded";
                if (param != null && param.Count > 0)
                {
                    byte[] byteArray = encoding.GetBytes(param.GetNvpString(true));
                    req.ContentLength = byteArray.Length;
                    using (System.IO.Stream stream = req.GetRequestStream())
                    {
                        stream.Write(byteArray, 0, byteArray.Length);
                        stream.Close();
                    }
                }
            }

            return req;
        }
Example #2
0
        /// <summary>
        /// 获取加密参数的url地址
        /// </summary>
        /// <param name="requestUrl">要请求的页面地址(含参数)</param>
        /// <param name="addSignature">是否自动加MD5签名(防止被篡改)</param>
        /// <param name="addTimestamp">是否自动加时间戳(DateTime.Now.Ticks)</param>
        /// <param name="encryptPassword">16个字母或数字组成的密钥(AES),如果为null或空字符串则不对参数进行加密</param>
        /// <param name="signatureValue">签名字串(输出参数)</param>
        /// <param name="timestampValue">时间戳(输出参数)</param>
        /// <returns>加密参数的url地址</returns>
        public static string GetSecureUrl(string requestUrlWithParameters, string signatureExt, string encryptPassword, out string signatureValue, out DateTime timestampValue)
        {
            if (requestUrlWithParameters == null)
            {
                requestUrlWithParameters = string.Empty;
            }

            Dictionary <string, string> parameters = null;

            string[] query = requestUrlWithParameters.Split('?');
            if (query.Length > 1)
            {
                parameters = WebUrlHelper.ParseQueryString(query[1]).ToDictionary();
            }

            return(GetSecureUrl(query[0], parameters, signatureExt, encryptPassword, out signatureValue, out timestampValue));
        }
Example #3
0
        /// <summary>
        /// 通过加密参数的url地址获取其中的参数
        /// </summary>
        /// <param name="secureUrl">加密参数的url地址或querystring部分</param>
        /// <param name="encryptPassword">16位字母或数字组成的解密密钥(AES)</param>
        /// <param name="errorCode">错误代码:0-成功,1-无效url地址,2-密钥为空,3-解密失败,4-签名无效,5-时间已过期</param>
        /// <returns>参数</returns>
        public static Dictionary <string, string> GetSecureParameters(string secureUrl, string signatureExt, string encryptPassword, int expireSeconds, out int errorCode)
        {
            string   signatureValue = null;
            DateTime timestampValue = DateTime.MinValue;

            errorCode = 0;

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(secureUrl))
            {
                errorCode = 1;//无效地址
                return(null);
            }

            if (secureUrl.IndexOf('?') != -1)
            {
                secureUrl = secureUrl.Split('?')[1];
            }

            if (secureUrl.IndexOf('=') == -1)
            {
                secureUrl = string.Empty;
            }

            if (secureUrl.IndexOf(SECUREURL_PARAMETER_NAME + "=", StringComparison.CurrentCultureIgnoreCase) != -1)
            {
                if (string.IsNullOrEmpty(encryptPassword))
                {
                    errorCode = 2;//密码无效
                    return(null);
                }
                try
                {
                    string[] tmp1 = secureUrl.Split('&');
                    string[] tmp2 = null;
                    foreach (string item in tmp1)
                    {
                        tmp2 = item.Split('=');
                        if (tmp2.Length == 2 && tmp2[0] == SECUREURL_PARAMETER_NAME)
                        {
                            secureUrl = tmp2[1];
                            break;
                        }
                    }
                    secureUrl = Encoding.UTF8.GetString(
                        SecurityHelper.AESDecrypt(HttpServerUtility.UrlTokenDecode(secureUrl), encryptPassword)
                        ).Replace("\0", string.Empty);
                }
                catch
                {
                    errorCode = 3;//解密失败
                    return(null);
                }
            }

            NameValueCollection nvp = WebUrlHelper.ParseQueryString(secureUrl);
            string tmp = null;

            for (int i = 0; i < nvp.Count; i++)
            {
                tmp = nvp.GetKey(i);
                if ("aspxautodetectcookiesupport".Equals(tmp, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }
                else if (SECUREURL_SIGNATURE_NAME.Equals(tmp, StringComparison.CurrentCultureIgnoreCase))
                {
                    signatureValue = nvp.Get(i).ToUpper();
                    continue;
                }
                else if (SECUREURL_TIMESTAMP_NAME.Equals(tmp, StringComparison.CurrentCultureIgnoreCase))
                {
                    timestampValue = new DateTime(nvp.Get(i).ToLong());
                    if (Math.Abs((timestampValue - DateTime.Now).TotalSeconds) > expireSeconds)
                    {
                        errorCode = 4;//时间已过期
                        return(null);
                    }
                }
                parameters.Add(nvp.GetKey(i), nvp.Get(i));
            }


            List <KeyValuePair <string, string> > orderedParameters = new List <KeyValuePair <string, string> >(parameters);

            orderedParameters.Sort(delegate(KeyValuePair <string, string> a, KeyValuePair <string, string> b)
            {
                return(a.Key.CompareTo(b.Key));
            });

            string paramNVP = orderedParameters.GetNvpString(false);

            string newSignature = null;

            if (paramNVP.Length > 0)
            {
                newSignature = SecurityHelper.MD5Encrypt(paramNVP + signatureExt).ToUpper();
            }
            if (signatureValue != null && signatureValue != newSignature)
            {
                errorCode = 5;//签名无效
            }

            return(parameters);
        }