当前位置: 首页>>代码示例>>C#>>正文


C# Web.HttpRequestBase类代码示例

本文整理汇总了C#中System.Web.HttpRequestBase的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestBase类的具体用法?C# HttpRequestBase怎么用?C# HttpRequestBase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpRequestBase类属于System.Web命名空间,在下文中一共展示了HttpRequestBase类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: WriteLog

        public void WriteLog(string userAgent, HttpRequestBase request, string platform, string browser, string user)
        {
            if (request == null) return;

            if (userAgent.IsNotSet())
            {
                LegacyDb.eventlog_create(null, this, "UserAgent string is empty.", EventLogTypes.Warning);
            }
            else
            {
                if (request.Browser != null && platform.ToLower().Contains("unknown") ||
                    browser.ToLower().Contains("unknown"))
                {
                    LegacyDb.eventlog_create(
                        null,
                        this,
                        "Unhandled UserAgent string:'{0}' /r/nPlatform:'{1}' /r/nBrowser:'{2}' /r/nSupports cookies='{3}' /r/nSupports EcmaScript='{4}' /r/nUserID='{5}'."
                            .FormatWith(
                                userAgent,
                                request.Browser.Platform,
                                request.Browser.Browser,
                                request.Browser.Cookies,
                                request.Browser.EcmaScriptVersion.ToString(),
                                user ?? String.Empty),
                        EventLogTypes.Warning);
                }
            }
        }
开发者ID:bugjohnyang,项目名称:YAFNET,代码行数:28,代码来源:UserAgentLogger.cs

示例2: GetClientIp

        public static string GetClientIp(HttpRequestBase request)
        {
            try
            {
                var userHostAddress = request.UserHostAddress ?? string.Empty;

                // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                // Could use TryParse instead, but I wanted to catch all exceptions
                if (!string.IsNullOrEmpty(userHostAddress))
                    IPAddress.Parse(userHostAddress);

                string xForwardedFor = request.ServerVariables["REMOTE_ADDR"];
                if (string.IsNullOrEmpty(xForwardedFor)) xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

                if (string.IsNullOrEmpty(xForwardedFor))
                    return userHostAddress;

                // Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

                // If we found any, return the last one, otherwise return the user host address
                return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
            }
            catch (Exception)
            {
                // Always return all zeroes for any failure (my calling code expects it)
                return "0.0.0.0";
            }
        }
开发者ID:howbigbobo,项目名称:DailyCode,代码行数:29,代码来源:HttpRequestUtil.cs

示例3: Context

        protected override void Context()
        {
            AccountService = MockRepository.GenerateStub<IAccountService>();

            Identity = new FakeIdentity(Username);
            _user = new FakePrincipal(Identity, null);

            HttpRequest = MockRepository.GenerateStub<HttpRequestBase>();
            HttpContext = MockRepository.GenerateStub<HttpContextBase>();
            HttpContext.Stub(x => x.Request).Return(HttpRequest);
            HttpContext.User = _user;

            _httpResponse = MockRepository.GenerateStub<HttpResponseBase>();
            _httpResponse.Stub(x => x.Cookies).Return(new HttpCookieCollection());
            HttpContext.Stub(x => x.Response).Return(_httpResponse);

            Logger = MockRepository.GenerateStub<ILogger>();
            WebAuthenticationService = MockRepository.GenerateStub<IWebAuthenticationService>();

            MappingEngine = MockRepository.GenerateStub<IMappingEngine>();
            AccountCreator = MockRepository.GenerateStub<IAccountCreator>();

            AccountController = new AccountController(AccountService, Logger, WebAuthenticationService, MappingEngine, null, AccountCreator);
            AccountController.ControllerContext = new ControllerContext(HttpContext, new RouteData(), AccountController);
        }
开发者ID:AcklenAvenue,项目名称:PRTools,代码行数:25,代码来源:given_an_account_controller_context.cs

示例4: GetClientIpAddress

        //Adapted from Noah Heldman's work at http://stackoverflow.com/a/10407992/17027
        public static bool GetClientIpAddress(HttpRequestBase request, out string remote)
        {
            try
            {
                var userHostAddress = request.UserHostAddress;

                //Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                //Could use TryParse instead, but I wanted to catch all exceptions
                IPAddress.Parse(userHostAddress);

                var xForwardedFor = request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED_FOR") ? request.ServerVariables["HTTP_X_FORWARDED_FOR"] :
                    request.ServerVariables.AllKeys.Contains("X_FORWARDED_FOR") ? request.ServerVariables["X_FORWARDED_FOR"] : "";

                if (string.IsNullOrWhiteSpace(xForwardedFor))
                {
                    remote = userHostAddress;
                    return true;
                }

                //Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

                //If we found any, return the last one, otherwise return the user host address
                remote = publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
                return true;
            }
            catch (Exception)
            {
                //Always return all zeroes for any failure
                remote = "0.0.0.0";
                return false;
            }
        }
开发者ID:denno-secqtinstien,项目名称:web,代码行数:34,代码来源:Utils.cs

示例5: GetFileHash

        /// <summary>
        /// Returns a hash of the supplied file.
        /// </summary>
        /// <param name="fname">The name of the file.</param>
        /// <param name="request">The current HttpRequest.</param>
        /// <returns>A Guid representing the hash of the file.</returns>
        public static Guid GetFileHash(string fname, HttpRequestBase request)
        {
            Guid hash;
            var localPath = request.RequestContext.
                HttpContext.Server.MapPath(fname.Replace('/', '\\'));

            using (var ms = new MemoryStream())
            {
                using (var fs = new FileStream(localPath,
                    FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    StreamCopy(fs, ms);
                }

                hash = new Guid(Md5.ComputeHash(ms.ToArray()));
                Guid check;
                if (!FileHash.TryGetValue(localPath, out check))
                {
                    FileHash.Add(localPath, hash);
                }
                else if (check != hash)
                {
                    FileHash[localPath] = hash;
                }
            }

            return hash;
        }
开发者ID:chergui,项目名称:DevConnections2013-HTML5-LOB,代码行数:34,代码来源:ViewHelper.cs

示例6: MapFile

        /// <summary>
        /// Maps data from the media file edit form to the media file object.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static void MapFile(HttpRequestBase request, string fieldSuffix, MediaFile file)
        {
            HttpPostedFileBase hpf = request.Files["file" + fieldSuffix];
            string externalfilename = request.Params["externalfile" + fieldSuffix];
            string filename = hpf.ContentLength == 0 ? externalfilename : hpf.FileName;
            file.Title = request.Params["title" + fieldSuffix];
            file.Description = request.Params["description" + fieldSuffix];
            file.SortIndex = ComLib.Extensions.NameValueExtensions.GetOrDefault<int>(request.Params, "SortIndex", file.SortIndex);
            file.IsPublic = true;
            if (file.LastWriteTime == DateTime.MinValue)
                file.LastWriteTime = DateTime.Now;

            // No Content?
            if (hpf.ContentLength == 0 && string.IsNullOrEmpty(externalfilename))
                return;

            // Get the file as a byte[]
            if (hpf.ContentLength > 0)
                file.Contents = ComLib.Web.WebUtils.GetContentOfFileAsBytes(hpf);

            // This will autoset the Name and Extension properties.
            file.FullNameRaw = filename;
            file.Length = hpf.ContentLength;
            
            // Set up the thumbnail.
            if (!file.IsExternalFile && file.IsImage)
                file.ToThumbNail(processLocalFileSystemFile: true);
        }
开发者ID:jespinoza711,项目名称:ASP.NET-MVC-CMS,代码行数:34,代码来源:MediaFileMapper.cs

示例7: VerifyAccess

		public virtual OutgoingWebResponse VerifyAccess(HttpRequestBase httpRequestInfo, out AccessToken accessToken) {
			Requires.NotNull(httpRequestInfo, "httpRequestInfo");

			AccessProtectedResourceRequest request = null;
			try {
				if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) {
					accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken);
					ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null reslut.");
					if (string.IsNullOrEmpty(accessToken.User) && string.IsNullOrEmpty(accessToken.ClientIdentifier)) {
						Logger.OAuth.Error("Access token rejected because both the username and client id properties were null or empty.");
						ErrorUtilities.ThrowProtocol(OAuth2Strings.InvalidAccessToken);
					}

					return null;
				} else {
					var response = new UnauthorizedResponse(new ProtocolException(OAuth2Strings.MissingAccessToken));

					accessToken = null;
					return this.Channel.PrepareResponse(response);
				}
			} catch (ProtocolException ex) {
				var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex);

				accessToken = null;
				return this.Channel.PrepareResponse(response);
			}
		}
开发者ID:OneCare,项目名称:dotnetopenid,代码行数:27,代码来源:ResourceServer.cs

示例8: AspNetRequest

 public AspNetRequest(HttpRequestBase request, IPrincipal user)
 {
     _request = request;
     Cookies = new HttpCookieCollectionWrapper(request.Cookies);
     User = user;
     ResolveFormAndQueryString();
 }
开发者ID:robink-teleopti,项目名称:SignalR,代码行数:7,代码来源:AspNetRequest.cs

示例9: RequestWantsToBeMobile

    public bool RequestWantsToBeMobile( HttpRequestBase request )
    {
      if( IsForcedMobileView( request ) )
      {
        cookieHelper.ForceViewMobileSite();
        return true;
      }

      var requestMode = cookieHelper.GetCurrentMode();

      switch( requestMode )
      {
        case SiteMode.NotSet:
          return IsMobileDevice( request );

        case SiteMode.Mobile:
          return true;

        case SiteMode.Desktop:
          return false;

        default:
          return false;
      }
    }
开发者ID:razorjam,项目名称:RazorJam.SparkViewEngineMobileViewLocator,代码行数:25,代码来源:MobileViewHelper.cs

示例10: GetImageFromRequest

        public static ListenTo.Shared.DO.Image GetImageFromRequest(HttpRequestBase request, string key)
        {
            ListenTo.Shared.DO.Image image = null;
            HttpPostedFileBase file = Helpers.FileHelpers.GetFileFromRequest(request, key);

            if (file != null && file.ContentLength != 0 )
            {
                try
                {
                    Byte[] fileData = GetContentFromHttpPostedFile(file);

                    if (IsFileImage(fileData))
                    {
                        image = ImageHelpers.GetImage(fileData);
                    }
                }
                catch (Exception e)
                {
                    //The file is not an image even though the headers are correct!
                    //Log the exception
                    throw;
                }
            }
            return image;
        }
开发者ID:listentorick,项目名称:ListenTo,代码行数:25,代码来源:FileHelpers.cs

示例11: NavigationModel

        public NavigationModel(HttpRequestBase httpRequest)
        {
            if(httpRequest == null)
                throw new ArgumentNullException("httpRequest");

            this._currentFilePath = httpRequest.FilePath;
        }
开发者ID:HansKindberg-Net,项目名称:HansKindberg,代码行数:7,代码来源:NavigationModel.cs

示例12: PopulatePhoneNumbers

        public static bool PopulatePhoneNumbers(UserViewModel uvm, HttpRequestBase request, out string validationError, out string flashErrorMessage)
        {
            flashErrorMessage = null;
            validationError = null;

            if (uvm == null || request == null)
                return false;

            // Find and (re)populate phone numbers.
            foreach (var phoneKey in request.Params.AllKeys.Where(x => x.StartsWith("phone_number_type"))) {
                var phoneTypeId = request[phoneKey].TryToInteger();
                var index = Regex.Match(phoneKey, @"\d+").Value;
                var phoneNumber = request[string.Format("phone_number[{0}]", index)];
                if (phoneTypeId.HasValue) {
                    // TODO: If the number contains an "x", split it out into number and extension.
                    var parts = phoneNumber.ToLower().Split('x');
                    string extension = "";
                    string number = Regex.Replace(parts[0], @"[^\d]", "");
                    if (parts.Length > 1) {
                        // Toss all the rest into the extension.
                        extension = string.Join("", parts.Skip(1));
                    }
                    // If the phone number is blank, just toss the entry - each form usually gets
                    // a blank spot added to it in case the user wants to add numbers, but he doesn't have to.
                    if (!string.IsNullOrEmpty(phoneNumber)) {
                        uvm.User.PhoneNumbers.Add(new PhoneNumber(request[string.Format("phone_number_id[{0}]", index)].TryToInteger(), phoneTypeId.Value, number, extension));
                    }
                } else {
                    flashErrorMessage = "Invalid phone number type - please select a valid phone type from the dropdown list.";
                    validationError = "Invalid phone type.";
                    return false;
                }
            }
            return true;
        }
开发者ID:jiadreamran,项目名称:HPAuthenticate,代码行数:35,代码来源:UserHelper.cs

示例13: TryGetRequestedRange

        private bool TryGetRequestedRange( HttpRequestBase request, out Range range )
        {
            var rangeHeader = request.Headers[ "Range" ];
            if ( string.IsNullOrEmpty( rangeHeader ) )
            {
                range = null;
                return false;
            }

            if ( !rangeHeader.StartsWith( RangeByteHeaderStart ) )
            {
                range = null;
                return false;
            }

            var parts = rangeHeader.Substring( RangeByteHeaderStart.Length ).Split( '-' );

            if ( parts.Length != 2 )
            {
                range = null;
                return false;
            }

            range = new Range
            {
                Start = string.IsNullOrEmpty( parts[ 0 ] ) ? (long?) null : long.Parse( parts[ 0 ] ),
                End = string.IsNullOrEmpty( parts[ 1 ] ) ? (long?) null : long.Parse( parts[ 1 ] )
            };
            return true;
        }
开发者ID:bmbsqd,项目名称:dynamic-media,代码行数:30,代码来源:BytesRangeResultHandler.cs

示例14: HandleResult

        public bool HandleResult( IResult result, IFormatInfo outputFormat, HttpRequestBase request, HttpResponseBase response )
        {
            response.AddHeader("Accept-Ranges", "bytes");

            Range range;
            if ( !TryGetRequestedRange( request, out range ) )
            {
                return false;
            }

            if (!ValidateIfRangeHeader(request, result))
            {
                return false;
            }

            var offset = range.Start ?? 0;
            var end = range.End.HasValue ? range.End.Value : result.ContentLength - 1;
            var length = end - offset + 1;

            response.AddHeader( "Content-Range", "bytes " + offset + "-" + end + "/" + result.ContentLength );
            response.StatusCode = 206;

            result.Serve( response, offset, length );
            return true;
        }
开发者ID:bmbsqd,项目名称:dynamic-media,代码行数:25,代码来源:BytesRangeResultHandler.cs

示例15: TryParseDeploymentInfo

        // { 
        //   'format':'basic'
        //   'url':'http://host/repository',
        //   'is_hg':true // optional
        // }
        public override DeployAction TryParseDeploymentInfo(HttpRequestBase request, JObject payload, string targetBranch, out DeploymentInfo deploymentInfo)
        {
            deploymentInfo = null;
            if (!String.Equals(payload.Value<string>("format"), "basic", StringComparison.OrdinalIgnoreCase))
            {
                return DeployAction.UnknownPayload;
            }

            string url = payload.Value<string>("url");
            if (String.IsNullOrEmpty(url))
            {
                return DeployAction.UnknownPayload;
            }

            string scm = payload.Value<string>("scm");
            bool is_hg;
            if (String.IsNullOrEmpty(scm))
            {
                // SSH [email protected] vs [email protected]
                is_hg = url.StartsWith("[email protected]", StringComparison.OrdinalIgnoreCase);
            }
            else
            {
                is_hg = String.Equals(scm, "hg", StringComparison.OrdinalIgnoreCase);
            }

            deploymentInfo = new DeploymentInfo();
            deploymentInfo.RepositoryUrl = url;
            deploymentInfo.RepositoryType = is_hg ? RepositoryType.Mercurial : RepositoryType.Git;
            deploymentInfo.Deployer = GetDeployerFromUrl(url);
            deploymentInfo.TargetChangeset = DeploymentManager.CreateTemporaryChangeSet(message: "Fetch from " + url);

            return DeployAction.ProcessDeployment;
        }
开发者ID:40a,项目名称:kudu,代码行数:39,代码来源:GenericHandler.cs


注:本文中的System.Web.HttpRequestBase类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。