Ejemplo n.º 1
0
        public void RelativeRootInWebApp()
        {
            var request = new System.Web.HttpRequest("~/abc.html", "http://www.google.com/", "?123=123");
            var response = new System.Web.HttpResponse(new StringWriter());
            var context = new System.Web.HttpContext(request, response);

            System.Web.HttpContext.Current = context;

            GetMockCache("~/temp");
        }
Ejemplo n.º 2
0
        public static MerchantTribe.Commerce.RequestContext GetFakeRequestContext(string fileName, string url, string querystring)
        {
            var result = new MerchantTribe.Commerce.RequestContext();

            var request = new System.Web.HttpRequest(fileName, url, querystring);
            var response = new System.Web.HttpResponse(new System.IO.StringWriter());
            System.Web.HttpContext httpContext = new System.Web.HttpContext(request, response);
            System.Web.HttpContextWrapper httpWrapper = new System.Web.HttpContextWrapper(httpContext);
            result.RoutingContext = new System.Web.Routing.RequestContext(httpWrapper,
                new System.Web.Routing.RouteData());

            return result;
        }
Ejemplo n.º 3
0
        internal PageRequest(ThreadEntity entity)
        {
            _innerRequest = entity.WebContext.Request;
            _values = new System.Collections.Specialized.NameValueCollection();
            _groupNvc = new System.Collections.Specialized.NameValueCollection();

            System.Text.RegularExpressions.GroupCollection _groupMatched = entity.URLItem.Regex.Match(entity.URL.Path).Groups;
            for (int i = 0; i < entity.URLItem.URLGroupsName.Length; i++) {
                string _key = entity.URLItem.URLGroupsName[i];
                _groupNvc.Add(_key, _groupMatched[_key].Value);
            }

            _values.Add(_innerRequest.QueryString);
            _values.Add(_innerRequest.Form);
            _values.Add(_groupNvc);
        }
Ejemplo n.º 4
0
 public static string RenderViewToString(string controllerName, string viewName, object viewData)
 {
     using (var writer = new StringWriter())
     {
         var routeData = new System.Web.Routing.RouteData();
         routeData.Values.Add("controller", controllerName);
         var httpRequest           = new System.Web.HttpRequest(null, "http://google.com", null);
         var contextWrapper        = new System.Web.HttpContextWrapper(new System.Web.HttpContext(httpRequest, new System.Web.HttpResponse(null)));
         var fakeControllerContext = new System.Web.Mvc.ControllerContext(contextWrapper, routeData, new FakeController());
         fakeControllerContext.RouteData = routeData;
         var razorViewEngine = new System.Web.Mvc.RazorViewEngine();
         var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);
         var viewContext     = new System.Web.Mvc.ViewContext(fakeControllerContext, razorViewResult.View, new System.Web.Mvc.ViewDataDictionary(viewData), new System.Web.Mvc.TempDataDictionary(), writer);
         razorViewResult.View.Render(viewContext, writer);
         return(writer.ToString());
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Uses the first two bytes of the hash code to form the directory, and then
        /// the bytes of the entire rawurl to form the file name. The extension has to
        /// stay as the same as the request to ensure the static file handler treats the
        /// image correctly.
        /// </summary>
        /// <param name="request">The requested image</param>
        /// <param name="size">The size of the image being rendered</param>
        /// <returns></returns>
        internal static string GetCachedResponseFile(System.Web.HttpRequest request, Size size)
        {
            // Create a single array of all the relevent bytes.
            var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(request.Path));

            return(Path.Combine(
                       request.ApplicationPath,
                       Path.Combine(
                           "App_Data\\Cache",
                           String.Concat(
                               String.Format("{0}", size.Width),
                               "\\",
                               String.Format("{0}", size.Height),
                               "\\",
                               String.Join("\\", SplitArray(encoded).ToArray()),
                               Path.GetExtension(request.CurrentExecutionFilePath)))));
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fromModel">paraModel</param>
        public static T BindeModel <T>(System.Web.HttpRequest httpRequest)
        {
            ////实体类赋值
            T paramodel = Activator.CreateInstance <T>();

            System.Reflection.PropertyInfo[] props = paramodel.GetType().GetProperties();
            for (int i = 0; i < props.Length; i++)
            {
                if (httpRequest.Form[props[i].Name] != null)
                {
                    object valtemp = System.Web.HttpUtility.UrlDecode(httpRequest.Form[props[i].Name]);
                    valtemp = ParseHelper.ToType(valtemp, props[i].PropertyType);
                    props[i].SetValue(paramodel, valtemp);
                }
            }
            return(paramodel);
        }
Ejemplo n.º 7
0
        public DataTable GetSSLBInfos(string strWhere, System.Web.HttpRequest context, params object[] objValues)//GetSSLBInfos(out string strError, string dwbm, string gh, System.Web.HttpRequest context)
        {
            //strError = "";
            //EDRS.Common.IceServicePrx iceprx = new IceServicePrx();
            XT_DM_AJLBBM bll = new XT_DM_AJLBBM(context);
            DataSet      ds  = bll.GetSSLBList(strWhere, objValues);

            if (ds != null && ds.Tables.Count > 0)
            {
                return(ds.Tables[0]);
            }
            return(null);

            //string msg = "";
            //msg = GetConfiguration(dwbm, gh, iceprx);
            //return iceprx.GetSSLBInfos(out strError);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 把接收到得参数复制到实体中
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="_request"></param>
        /// <param name="_ShopMenu"></param>
        /// <returns></returns>
        public static T ConvertRequestToModel <T>(T _SaveModel, T _ShopMenu)
        {
            System.Web.HttpRequest _request = System.Web.HttpContext.Current.Request;
            Type myType   = _ShopMenu.GetType();
            Type saveType = _SaveModel.GetType();

            //复制Post的参数
            for (int i = 0; i < _request.Form.Count; i++)
            {
                if (_request.Form.Keys[i] == null)
                {
                    continue;
                }
                PropertyInfo pinfo    = myType.GetProperty(_request.Form.Keys[i]);
                PropertyInfo saveInfo = saveType.GetProperty(_request.Form.Keys[i]);
                if (saveInfo != null)
                {
                    object v = pinfo.GetValue(_ShopMenu, null);
                    try
                    {
                        saveInfo.SetValue(_SaveModel, v, null);
                    }
                    catch (Exception) { }
                }
            }

            //复制Get的参数
            for (int i = 0; i < _request.QueryString.Count; i++)
            {
                if (_request.QueryString.Keys[i] != null)
                {
                    PropertyInfo pinfo    = myType.GetProperty(_request.QueryString.Keys[i]);
                    PropertyInfo saveInfo = saveType.GetProperty(_request.QueryString.Keys[i]);
                    if (saveInfo != null)
                    {
                        object v = pinfo.GetValue(_ShopMenu, null);
                        if (v != null)
                        {
                            saveInfo.SetValue(_SaveModel, v, null);
                        }
                    }
                }
            }
            return(_SaveModel);
        }
Ejemplo n.º 9
0
        public String ObjectToHtml(Object valueObject, String parameterName, System.Web.HttpRequest request)
        {
            String html       = null;
            String dateFormat = (String)GetConfiguration()["dateFormat"];

            log.Debug("dateformat: " + dateFormat);

            html = "<input type=text size=11 name=\"" + parameterName + "\"";

            if (valueObject != null)
            {
                html += (" value=\"" + ((DateTime)valueObject).ToString(dateFormat, enUS) + "\"");
            }

            html += ("> (" + dateFormat + ")");

            return(html);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Due to differences in url escape between xhtml and wml (adapters related). Returns true or false
        /// </summary>
        /// <param name="req">current Request</param>
        /// <returns>True if the URL must be encodes, false otherwise.</returns>
        public static bool UrlAttributeMustBeEncoded(System.Web.HttpRequest req)
        {
            bool res = false;

            if (req.Browser.IsMobileDevice)
            {
                string prefRendType = req.Browser.PreferredRenderingType;
                if (prefRendType.StartsWith("xhtml") || prefRendType.StartsWith("html"))
                {
                    res = false;
                }
                else
                {
                    res = true;
                }
            }
            return(res);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Returns non-zero if the browser supports HTML with inline images.
        /// </summary>
        /// <param name="req">An HttpRequest that will be used to determine whether or not the user's browser supports inline images.</param>
        /// <returns></returns>
        public static bool BrowserSupportsInlineImages(System.Web.HttpRequest req)
        {
            string inlineImages = req.Form["InlineImages"];

            bool supportsInlineImages;

            if (inlineImages != null)
            {
                supportsInlineImages = (inlineImages.ToLowerInvariant() == "true");
            }
            else
            {
                int version;
                supportsInlineImages = !IsIE(req, out version) || version >= 9;                 // IE9 supports up to 4GB in a data uri (http://msdn.microsoft.com/en-us/ie/ff468705.aspx#_DataURI)
            }

            return(supportsInlineImages);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 读取一个多键cookie. 如果读取失败, 返回空
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="key">要读取的键名</param>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="server"></param>
        /// <returns>返回读到的值或空.</returns>
        public static string ReadCookie(string cookieName, string key, System.Web.HttpRequest request,
                                        System.Web.HttpResponse response, System.Web.HttpServerUtility server)
        {
            if (CheckCookie(cookieName, request) == false)
            {
                return("");
            }
            System.Web.HttpCookie objCookie = request.Cookies[cookieName];

            try
            {
                return(server.UrlDecode(objCookie.Values[key]));
            }
            catch (Exception ex)
            {
                return("");
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Authenticate a request from Maestrano using HTTP Basic Authentication
        /// </summary>
        /// <param name="request">An HttpRequest object</param>
        /// <returns>true if the authentication is successful, false otherwise</returns>
        public bool Authenticate(System.Web.HttpRequest request)
        {
            string authHeader    = request.Headers["Authorization"];
            bool   authenticated = false;

            // RFC 2617 sec 1.2, "scheme" name is case-insensitive
            if (authHeader != null && authHeader.ToLower().StartsWith("basic"))
            {
                string   encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
                Encoding encoding         = Encoding.GetEncoding("iso-8859-1");
                string   usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
                int      seperatorIndex   = usernamePassword.IndexOf(':');
                var      apiId            = usernamePassword.Substring(0, seperatorIndex);
                var      apiKey           = usernamePassword.Substring(seperatorIndex + 1);
                authenticated = Authenticate(apiId, apiKey);
            }
            return(authenticated);
        }
 /// <summary>
 /// Gets the username.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <returns></returns>
 public static string GetUsername(System.Web.HttpRequest request)
 {
     try
     {
         return(request.LogonUserIdentity.Name);
     }
     catch (InvalidOperationException ioex)
     {
         if (System.Web.HttpContext.Current.User != null)
         {
             return(System.Web.HttpContext.Current.User.Identity.Name);
         }
         else
         {
             return(string.Empty);
         }
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        ///  自定义全局异常
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            //1:获取异常对象
            Exception ex = filterContext.Exception;
            //2:记录异常日志
            StringBuilder str = new StringBuilder();

            str.AppendLine("\r\n.捕获异常信息:");
            string iP = string.Empty;

            System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request;
            if (!string.IsNullOrEmpty(Request.ServerVariables["HTTP_VIA"]))
            {
                iP = Convert.ToString(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            }
            if (string.IsNullOrEmpty(iP))
            {
                iP = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]);
            }
            str.AppendLine("IP:" + iP);
            str.AppendLine("浏览器:" + Request.Browser.Browser);
            str.AppendLine("浏览器版本:" + Request.Browser.MajorVersion);
            str.AppendLine("操作系统:" + Request.Browser.Platform);
            str.AppendLine("错误信息:");
            str.AppendLine("错误页面:" + Request.Url);
            str.AppendLine("错误信息:" + ex.Message);
            str.AppendLine("错误源:" + ex.Source);
            str.AppendLine("异常方法:" + ex.TargetSite);
            str.AppendLine("堆栈信息:" + ex.StackTrace);
            LogHelper.ErrorLog(typeof(DExceptionFilterAttribute), str.ToString());
            //3:篡改Response
            filterContext.Response =
                filterContext.Request.CreateResponse(HttpStatusCode.OK, new HCQ2_Model.ViewModel.WebAPI.WebApiResultJsonModel()
            {
                errcode = WebResultCode.Exception,
                errmsg  = ex.Message,
                value   = null
            });
            //3:重定向友好页面
            //filterContext.Result = new RedirectResult(Request.ApplicationPath + "/error.html");
            //4:标记异常已经处理完毕
            //filterContext.ExceptionHandled = true;
            base.OnException(filterContext);
        }
Ejemplo n.º 16
0
        private static void CollectContextProperties(IDictionary <string, object> properties)
        {
            if (!properties.ContainsKey("WorkingMode"))
            {
                properties.Add("WorkingMode", RepositoryEnvironment.WorkingMode.RawValue);
            }

            if (!properties.ContainsKey("IsHttpContext"))
            {
                var ctx = System.Web.HttpContext.Current;
                properties.Add("IsHttpContext", ctx == null ? "no" : "yes");

                if (ctx != null)
                {
                    System.Web.HttpRequest req = null;
                    try
                    {
                        req = ctx.Request;
                    }
                    catch
                    {
                        // ignored
                    }
                    if (req != null)
                    {
                        if (!properties.ContainsKey("Url"))
                        {
                            properties.Add("Url", ctx.Request.Url);
                        }
                        if (!properties.ContainsKey("Referrer"))
                        {
                            properties.Add("Referrer", ctx.Request.UrlReferrer);
                        }
                    }
                    else
                    {
                        if (!properties.ContainsKey("Url"))
                        {
                            properties.Add("Url", "// not available //");
                        }
                    }
                }
            }
        }
        public static void AuthenticateRequest(System.Web.HttpContext context, System.Web.HttpRequest request)
        {
            try
            {
                System.Web.HttpCookie authCookie = context.Request.Cookies[
                    System.Web.Security.FormsAuthentication.FormsCookieName];

                if (authCookie != null)
                {
                    System.Web.Security.FormsAuthenticationTicket authTicket =
                        System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value);

                    // Extract data, find authenticated user and attach it to context
                    string[] userInfo = authTicket.UserData.Split('|');
                    if (userInfo.Length == 2)
                    {
                        int             index = Convert.ToInt32(userInfo[0]);
                        Membership.User user  = Repository.Memory.Users.Instance.GetUser(index);
                        if (user != null && user.Id > 0 && Convert.ToInt32(userInfo[1]) == user.Id)
                        {
                            user.Identitiy.Ticket = authTicket;

                            context.User = user;
                            System.Threading.Thread.CurrentPrincipal = user;
                        }
                        else
                        {
                            // Cookie sucks
                            authCookie.Expires = DateTime.UtcNow.AddYears(-1);
                            context.Request.Cookies.Add(authCookie);
                            context.Response.Cookies.Add(authCookie);
                            SignOut();

                            context.User = new DomainModel.Membership.AnonymousUser();
                            System.Threading.Thread.CurrentPrincipal = context.User;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Exception:{0}", ex.ToString()));
            }
        }
Ejemplo n.º 18
0
        public static void RndUrl()
        {
            System.Web.HttpRequest  Request  = System.Web.HttpContext.Current.Request;
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;

            if (Request["Rnd"] == null || Request["Rnd"].Trim() == String.Empty)
            {
                String time0 = DateTime.Now.ToString();
                time0 = FormsAuthentication.HashPasswordForStoringInConfigFile(time0, "MD5");
                if (Request.RawUrl.IndexOf("?") < 0)
                {
                    Response.Redirect(Request.RawUrl + "?Rnd=" + time0, true);
                }
                else
                {
                    Response.Redirect(Request.RawUrl + "&Rnd=" + time0, true);
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 删除一个cookie.
        /// </summary>
        /// <param name="cookieName">cookie名</param>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <returns>如果成功删除, 返回真, 否则返回假</returns>
        public static bool RemoveCookie(string cookieName, System.Web.HttpRequest request, System.Web.HttpResponse response)
        {
            if (CheckCookie(cookieName, request) == false)
            {
                return(true);
            }

            System.Web.HttpCookie objCookie = request.Cookies[cookieName];
            objCookie.Expires = DateTime.Now.AddMinutes(-1);
            try
            {
                response.AppendCookie(objCookie);
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 20
0
        public Result UpLoadFile()
        {
            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            // string taskID = request["ETID"].ToString().Trim();
            //int ETClass = Convert.ToInt32(request["ETClass"].ToString().Trim());
            // int tid = int.Parse(taskID);
            //var task = service.FindEntity<MyTest>(m => m.Id == tid);
            //if (task == null) return new Result("-1", "任务为空");

            System.Web.HttpFileCollection fileCollection = request.Files;
            if (fileCollection.Count < 1)
            {
                return(new Result("-1", "上传失败,文件为空"));
            }
            var fileinfo = UploadHelper.UploadFile(fileCollection[0]);

            if (fileinfo.IsSuccess == false)
            {
                return(new Result("-1", "上传失败"));
            }

            FileCenter newfile = new FileCenter();

            newfile.CreateDT     = DateTime.Now;
            newfile.EndUserID    = 0;
            newfile.RealName     = fileinfo.OldFileName;
            newfile.FileName     = fileinfo.NewFileName;
            newfile.FileUrl      = fileinfo.FilePath;
            newfile.FileSize     = fileCollection[0].ContentLength / 1000;
            newfile.CreateUserID = service.GetPersonID(ControllerContext.Request.Properties["WorkNo"].ToString());//请求人ID
            if (service.Insert <FileCenter>(newfile))
            {
                //ET_TaskFiled ET_TaskFiled = new ET_TaskFiled();
                //ET_TaskFiled.ETID = tid;
                //ET_TaskFiled.ETClass = ETClass;
                //ET_TaskFiled.FiledID = newfile.ID;
                //if (service.Insert<ET_TaskFiled>(ET_TaskFiled))
                //{
                return(new Result("0", newfile.ID.ToString()));
                //}
            }
            return(new Result("-1", "上传失败"));
        }
Ejemplo n.º 21
0
 /// <summary>
 /// 修改一个单键cookie的值. 如果指定的cookie不存在, 返回false
 /// </summary>
 /// <param name="cookieName"></param>
 /// <param name="value"></param>
 /// <param name="request"></param>
 /// <param name="response"></param>
 /// <param name="server"></param>
 /// <returns>修改成功,返回真, 否则返回假</returns>
 public static bool ChangeKeyValue(string cookieName, string value, System.Web.HttpRequest request,
                                   System.Web.HttpResponse response, System.Web.HttpServerUtility server)
 {
     if (CheckCookie(cookieName, request) == false)
     {
         return(false);
     }
     try
     {
         System.Web.HttpCookie objCookie = request.Cookies[cookieName];
         objCookie.Value = server.UrlEncode(value);
         response.AppendCookie(objCookie);
     }
     catch (Exception ex)
     {
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// 获取支付宝GET过来通知消息,并以“参数名=参数值”的形式组成数组
        /// 创建人:孙佳杰 时间:2015.1.16
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        private static SortedDictionary <string, string> GetRequestGet(System.Web.HttpRequest request)
        {
            int i = 0;
            SortedDictionary <string, string> sArray = new SortedDictionary <string, string>();
            NameValueCollection coll;

            //Load Form variables into NameValueCollection variable.
            coll = request.QueryString;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], request.QueryString[requestItem[i]]);
            }

            return(sArray);
        }
Ejemplo n.º 23
0
        public virtual IEnumerable SyncCCPaymentMethods(PXAdapter adapter)
        {
            string methodName = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            CustomerPaymentMethod currentPaymentMethod = CustomerPaymentMethod.Current;

            PXTrace.WriteInformation($"{methodName}. CCProcessingCenterID:{currentPaymentMethod.CCProcessingCenterID}; UserName:{this.Base.Accessinfo.UserName}");
            IEnumerable ret = adapter.Get();

            bool isCancel = false;

            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            var cancelStr = request.Form.Get("__CLOSECCHFORM");

            bool.TryParse(cancelStr, out isCancel);
            if (isCancel)
            {
                return(ret);
            }

            if (currentPaymentMethod.CCProcessingCenterID == null)
            {
                CustomerPaymentMethod.Cache.SetDefaultExt <CustomerPaymentMethod.cCProcessingCenterID>(currentPaymentMethod);
                CustomerPaymentMethod.Cache.SetDefaultExt <CustomerPaymentMethod.customerCCPID>(currentPaymentMethod);
            }
            var graph = PXGraph.CreateInstance <CCCustomerInformationManagerGraph>();

            ICCPaymentProfileAdapter       paymentProfile = new GenericCCPaymentProfileAdapter <CustomerPaymentMethod>(CustomerPaymentMethod);
            ICCPaymentProfileDetailAdapter profileDetail  = new GenericCCPaymentProfileDetailAdapter <CustomerPaymentMethodDetail, PaymentMethodDetail>(CustomerPaymentMethodDetail, PaymentMethodDetail);
            bool isIDFilled = CCProcessingHelper.IsCCPIDFilled(this.Base, CustomerPaymentMethod.Current.PMInstanceID);

            if (!isIDFilled)
            {
                graph.GetNewPaymentProfiles(this.Base, paymentProfile, profileDetail);
            }
            else
            {
                graph.GetPaymentProfile(this.Base, paymentProfile, profileDetail);
            }
            this.Base.Persist();
            return(ret);
        }
Ejemplo n.º 24
0
        public static bool IsMobile()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            if (context != null)
            {
                System.Web.HttpRequest request = context.Request;
                if (request.Browser.IsMobileDevice)
                {
                    return(true);
                }
                string MobileUserAgent = "iphone|android|nokia|zte|huawei|lenovo|samsung|motorola|sonyericsson|lg|philips|gionee|htc|coolpad|symbian|sony|ericsson|mot|cmcc|iemobile|sgh|panasonic|alcatel|cldc|midp|wap|mobile|blackberry|windows ce|mqqbrowser|ucweb";

                Regex MOBILE_REGEX = new Regex(MobileUserAgent);
                if (string.IsNullOrEmpty(request.UserAgent) && MOBILE_REGEX.IsMatch(request.UserAgent.ToLower()))
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 返回美团当前请求对应的签名  add by caoheyang 20150421
        /// </summary>
        /// <param name="httpRequest">上下文数据对象</param>
        /// <returns></returns>
        public string GetSig(System.Web.HttpRequest httpRequest)
        {
            List <string> paras = new List <string>();

            foreach (string key in httpRequest.QueryString.Keys)
            {
                if (key != "sig")
                {
                    string valtemp = System.Web.HttpUtility.UrlDecode(System.Web.HttpUtility.UrlDecode(httpRequest.QueryString[key]));
                    paras.Add(key + "=" + (valtemp ?? ""));
                }
            }
            paras.Sort(new NewStringComparer());  //TODO待长时间验证  目前慎用
            int    index   = httpRequest.Url.ToString().IndexOf('?');
            string url     = (index < 0 ? httpRequest.Url.ToString() : httpRequest.Url.ToString().Substring(0, index)) + "?";
            string waimd5  = url + string.Join("&", paras) + consumer_secret; //consumer_secret
            string sigtemp = ETS.Security.MD5.DefaultEncrypt(waimd5).ToLower();

            return(sigtemp);
        }
Ejemplo n.º 26
0
 public static string GetCallingIPAddress(System.Web.HttpRequest request)
 {
     try
     {
         var retval = request.UserHostAddress;
         if (string.IsNullOrEmpty(retval))
         {
             retval = request.ServerVariables["REMOTE_ADDR"];
         }
         if (string.IsNullOrEmpty(retval))
         {
             retval = null;
         }
         return(retval);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
        private static XmlElement CreateRequestElement(XmlDocument oRoot)
        {
            System.Web.HttpRequest req      = System.Web.HttpContext.Current.Request;
            XmlElement             oRequest = CreateNode(oRoot, "Request", null, null);

            oRequest.AppendChild(CreateNode(oRoot, "Client-IP", null, req.UserHostAddress));
            oRequest.AppendChild(CreateNode(oRoot, "Client-Host", null, req.UserHostName));
            oRequest.AppendChild(CreateNode(oRoot, "URL", null, req.Url.ToString()));
            //oSession.AppendChild(CreateNode(oRoot,"rawURL",null,req.RawUrl));
            if (req.UrlReferrer != null)
            {
                oRequest.AppendChild(CreateNode(oRoot, "URL-Referrer", null, req.UrlReferrer.ToString()));
            }
            oRequest.AppendChild(CreateNode(oRoot, "QueryString", null, req.QueryString.ToString()));
            oRequest.AppendChild(CreateNode(oRoot, "Form", null, req.Form.ToString()));
            //oSession.AppendChild(CreateNode(oRoot,"ServerVaribles",null,req.ServerVariables.ToString()));
            //oSession.AppendChild(CreateNode(oRoot,"Param",null,req.Params.ToString()));

            return(oRequest);
        }
Ejemplo n.º 28
0
        public String ObjectToHtml(Object valueObject, String parameterName, System.Web.HttpRequest request)
        {
            System.String html = null;

            System.String cols = (String)GetConfiguration()["cols"];
            System.String rows = (String)GetConfiguration()["rows"];

            html = "<textarea rows=" + rows + " cols=" + cols + " name=\"" + parameterName + "\">";

            if (valueObject != null)
            {
                html += valueObject.ToString();
            }

            html += "</textarea>";

            log.Debug("generated text area control : " + html);

            return(html);
        }
Ejemplo n.º 29
0
        public string GetViaIP()
        {
            string viaIp = "";

            try
            {
                System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;

                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    viaIp = request.UserHostAddress;
                }
            }
            catch (Exception e)
            {
                this.SaveLog(e);
            }

            return(viaIp);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 设置一个cookie的过期时间
        /// </summary>
        /// <param name="cookieName"></param>
        /// <param name="dtObsolete"></param>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <returns>设置成功返回真, 否则返回假</returns>
        public static bool SetCookieExpire(string cookieName, DateTime dtObsolete,
                                           System.Web.HttpRequest request, System.Web.HttpResponse response)
        {
            if (CheckCookie(cookieName, request) == false)
            {
                return(false);
            }
            System.Web.HttpCookie objCookie = request.Cookies[cookieName];
            objCookie.Expires = dtObsolete;

            try
            {
                response.AppendCookie(objCookie);
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 31
0
        //Function to break URL into Controller and Action
        private System.Web.Routing.RouteData getURLActionController(string fullUrl)
        {
            // Split the url to url + query string
            var    questionMarkIndex = fullUrl.IndexOf('?');
            string queryString       = null;
            string url = fullUrl;

            if (questionMarkIndex != -1) // There is a QueryString
            {
                url         = fullUrl.Substring(0, questionMarkIndex);
                queryString = fullUrl.Substring(questionMarkIndex + 1);
            }

            // Arranges
            var request     = new System.Web.HttpRequest(null, url, queryString);
            var response    = new System.Web.HttpResponse(new System.IO.StringWriter());
            var httpContext = new System.Web.HttpContext(request, response);

            return(System.Web.Routing.RouteTable.Routes.GetRouteData(new System.Web.HttpContextWrapper(httpContext)));
        }
Ejemplo n.º 32
0
        public bool manage_session(System.Web.HttpRequest request,
                                   System.Web.HttpResponse response,
                                   string cookieName,
                                   IStatusHandler handler)
        {
            error_descr_ = "";
            if (null == cookieName || "" == cookieName)
            {
                throw new System.Exception("Access Manager Cookie name must be setupped throught 'AccessManager.Cookie' variable in web.config");
            }
            try
            {
                if (null != request.Params["login"] &&
                    null != request.Params["password"])
                {
                    logon(
                        request.Params["login"].ToString(),
                        request.Params["password"].ToString());


                    if (request.Params["remember"] != null)
                    {
                        response.Cookies[cookieName].Value   = ctx_.ToString();
                        response.Cookies[cookieName].Expires = DateTime.Now.AddDays(32);
                    }

                    handler.on_logon();
                }

                if (null != request.Params["logoff"] && request.Params["logoff"].Equals("true"))
                {
                    logof();
                    return(handler.on_logof());
                }
            }
            catch (System.Exception ee)
            {
                error_descr_ = ee.Message;
            }
            return(true);
        }
Ejemplo n.º 33
0
        public static string rate_it(System.Data.SqlClient.SqlConnection conn, System.Web.HttpRequest req)
        {
            int idx  = Int32.Parse(req["idx"].ToString());
            int vote = Int32.Parse(req["vote"].ToString());

            SqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select current_rating,votes from TestRating where idx=" + idx.ToString() + ";";
            int current_rating = 0;
            int votes          = 0;

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    reader.Read();
                    current_rating = (int)reader[0];
                    votes          = (int)reader[1];
                    reader.Close();
                }
                else
                {
                    reader.Close();
                    SqlCommand cmd2 = conn.CreateCommand();
                    cmd2.CommandText = String.Format("insert into TestRating (idx,current_rating,votes) values({0},0,0);", idx);
                    cmd2.ExecuteNonQuery();
                }
            }

            current_rating = (current_rating * votes + vote) / (votes + 1);
            votes++;

            SqlCommand cmd3 = conn.CreateCommand();

            cmd3.CommandText = String.Format(@"
update TestRating set current_rating={0},votes={1} where idx={2};
update Tests set rating={0} where Id={2};
", current_rating, votes, idx);
            cmd3.ExecuteNonQuery();
            return(current_rating.ToString());
        }
 public XmlRpcHttpRequest(System.Web.HttpRequest request)
 {
     m_req = request;
 }