• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Web.HttpRequestBase类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: GetUploadedImages

        public IEnumerable<Image> GetUploadedImages(HttpRequestBase request, params string[] imageDefinitionKeys)
        {
            List<Image> images = new List<Image>();

            foreach (string inputTagName in request.Files)
            {
                HttpPostedFileBase file = request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    // upload the image to filesystem
                    if (IsNotImage(file))
                    {
                        throw new ValidationException(string.Format("File '{0}' is not an image file (*.jpg)", file.FileName));
                    }

                    Image image = new Image
                    {
                        FileName = Guid.NewGuid(),
                        Description = Path.GetFileName(file.FileName)
                    };

                    file.SaveAs(imageFileService.GetFullPath(image.FileNameAsString));

                    // convert the image to main and thumb sizes
                    imageService.CreateSizedImages(image, imageDefinitionKeys);

                    File.Delete(imageFileService.GetFullPath(image.FileNameAsString));

                    images.Add(image);
                }
            }

            return images;
        }
开发者ID:bertusmagnus,项目名称:Sutekishop,代码行数:34,代码来源:HttpFileService.cs


示例17: UnbindInternal

        protected Saml2Request UnbindInternal(HttpRequestBase request, Saml2Request saml2RequestResponse, X509Certificate2 signatureValidationCertificate)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (saml2RequestResponse == null)
                throw new ArgumentNullException("saml2RequestResponse");

            if (signatureValidationCertificate == null)
            {
                throw new ArgumentNullException("signatureValidationCertificate");
            }
            if (signatureValidationCertificate.PublicKey == null)
            {
                throw new ArgumentException("No Public Key present in Signature Validation Certificate.");
            }
            if (!(signatureValidationCertificate.PublicKey.Key is DSA || signatureValidationCertificate.PublicKey.Key is RSACryptoServiceProvider))
            {
                throw new ArgumentException("The Public Key present in Signature Validation Certificate must be either DSA or RSACryptoServiceProvider.");
            }

            saml2RequestResponse.SignatureValidationCertificate = signatureValidationCertificate;

            return saml2RequestResponse;
        }
开发者ID:hallatore,项目名称:ITfoxtec.SAML2,代码行数:25,代码来源:Saml2Binding.cs


示例18: SetSelectedPath

        /// <summary>
        /// Identifies the currently selected path, starting from the selected node.
        /// </summary>
        /// <param name="menuItems">All the menuitems in the navigation menu.</param>
        /// <param name="currentRequest">The currently executed request if any</param>
        /// <param name="currentRouteData">The current route data.</param>
        /// <returns>A stack with the selection path being the last node the currently selected one.</returns>
        public static Stack<MenuItem> SetSelectedPath(IEnumerable<MenuItem> menuItems, HttpRequestBase currentRequest, RouteValueDictionary currentRouteData) {
            // doing route data comparison first and if that fails, fallback to string-based URL lookup
            var path = SetSelectedPath(menuItems, currentRequest, currentRouteData, false) 
                    ?? SetSelectedPath(menuItems, currentRequest, currentRouteData, true);

            return path;
        }
开发者ID:RasterImage,项目名称:Orchard,代码行数:14,代码来源:NavigationHelper.cs


示例19: ProcessFormCollection

        public TaskTypeResult ProcessFormCollection(int taskID, int userID, FormCollection collection, HttpRequestBase request)
        {
            DidacheDb db = new DidacheDb();

            Task task = db.Tasks.Find(taskID);
            UserTaskData data = db.UserTasks.SingleOrDefault(d => d.TaskID == taskID && d.UserID == userID);

            // CREATE POST
            InteractionThread thread = new InteractionThread();
            thread.UserID = userID;
            thread.TotalReplies = 0;
            thread.Subject = "Assignment: " + task.Name;
            thread.TaskID = taskID;
            thread.ThreadDate = DateTime.Now;
            db.InteractionThreads.Add(thread);
            db.SaveChanges();

            InteractionPost post = new InteractionPost();
            post.IsApproved = true;
            post.PostContent = request["usercomment"];
            post.PostContentFormatted = Interactions.FormatPost(request["usercomment"]);
            post.PostDate = DateTime.Now;
            post.ReplyToPostID = 0;
            post.ThreadID = thread.ThreadID;
            post.UserID = userID;
            post.Subject = "RE: Assignment: " + task.Name;
            post.TaskID = taskID;
            db.InteractionPosts.Add(post);
            db.SaveChanges();

            return new TaskTypeResult() { Success = true, UrlHash = "thread-" + thread.ThreadID };
        }
开发者ID:dallasseminary,项目名称:Didache,代码行数:32,代码来源:RespondToDiscussion.cs


示例20: SendAsset

        void SendAsset(HttpRequestBase request, HttpResponseBase response, Bundle bundle, IAsset asset)
        {
            response.ContentType = bundle.ContentType;

            var actualETag = "\"" + asset.Hash.ToHexString() + "\"";
            if(request.RawUrl.Contains(asset.Hash.ToHexString())) {
                CacheLongTime(response, actualETag);
            }
            else {
                NoCache(response);
            }

            var givenETag = request.Headers["If-None-Match"];
            if (!disableHashCheck && givenETag == actualETag)
            {
                SendNotModified(response);
            }
            else
            {
                using (var stream = asset.OpenStream())
                {
                    stream.CopyTo(response.OutputStream);
                }
            }
        }
开发者ID:justanswer,项目名称:cassette,代码行数:25,代码来源:AssetRequestHandler.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Web.HttpResponse类代码示例发布时间:2022-05-26
下一篇:
C# Web.HttpRequest类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap