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


C# HttpContextWrapper.RewritePath方法代码示例

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


在下文中一共展示了HttpContextWrapper.RewritePath方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RenderPartialFromPath

        public static string RenderPartialFromPath(this IFubuPage page, string path)
        {
            RouteCollection routes = RouteTable.Routes;
            string originalPath = HttpContext.Current.Request.Path;
            HttpContext.Current.RewritePath(path);
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            RouteData data = routes.GetRouteData(httpContext);
            IHttpHandler httpHandler = data.RouteHandler.GetHttpHandler(new RequestContext(httpContext, data));
            httpHandler.ProcessRequest(HttpContext.Current);
            httpContext.RewritePath(originalPath, false);

            return "";
        }
开发者ID:statianzo,项目名称:MvcToFubu,代码行数:13,代码来源:FubuPageExtensions.cs

示例2: IsAccessibleToUser

        /// <summary>
        /// Determines whether node is accessible to user.
        /// </summary>
        /// <param name="controllerTypeResolver">The controller type resolver.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="context">The context.</param>
        /// <param name="node">The node.</param>
        /// <returns>
        /// 	<c>true</c> if accessible to user; otherwise, <c>false</c>.
        /// </returns>
        public bool IsAccessibleToUser(IControllerTypeResolver controllerTypeResolver, DefaultSiteMapProvider provider, HttpContext context, SiteMapNode node)
        {
            // Is security trimming enabled?
            if (!provider.SecurityTrimmingEnabled)
            {
                return true;
            }

            // Is it an external node?
            var nodeUrl = node.Url;
            if (nodeUrl.StartsWith("http") || nodeUrl.StartsWith("ftp"))
            {
                return true;
            }

            // Is it a regular node?
            var mvcNode = node as MvcSiteMapNode;
            if (mvcNode == null)
            {
                throw new AclModuleNotSupportedException(
                    Resources.Messages.AclModuleDoesNotSupportRegularSiteMapNodes);
            }

            // Clickable? Always accessible.
            if (mvcNode.Clickable == false)
            {
                return true;
            }

            // Time to delve into the AuthorizeAttribute defined on the node.
            // Let's start by getting all metadata for the controller...
            var controllerType = controllerTypeResolver.ResolveControllerType(mvcNode.Area, mvcNode.Controller);
            if (controllerType == null)
            {
                return false;
            }

            // Find routes for the sitemap node's url
            HttpContextBase httpContext = new HttpContextWrapper(context);
            string originalPath = httpContext.Request.Path;
            var originalRoutes = RouteTable.Routes.GetRouteData(httpContext);
            httpContext.RewritePath(nodeUrl, true);

            HttpContextBase httpContext2 = new HttpContext2(context);
            RouteData routes = mvcNode.GetRouteData(httpContext2);
            if (routes == null)
            {
                return true; // Static URL's will have no route data, therefore return true.
            }
            foreach (var routeValue in mvcNode.RouteValues)
            {
                routes.Values[routeValue.Key] = routeValue.Value;
            }
            if (!routes.Route.Equals(originalRoutes.Route) || originalPath != nodeUrl || mvcNode.Area == String.Empty)
            {
                routes.DataTokens.Remove("area");
                //routes.DataTokens.Remove("Namespaces");
                //routes.Values.Remove("area");
            }
            var requestContext = new RequestContext(httpContext, routes);

            // Create controller context
            var controllerContext = new ControllerContext();
            controllerContext.RequestContext = requestContext;
            try
            {
                string controllerName = requestContext.RouteData.GetRequiredString("controller");
                controllerContext.Controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName) as ControllerBase;
            }
            catch
            {
                try
                {
                    controllerContext.Controller = Activator.CreateInstance(controllerType) as ControllerBase;
                }
                catch
                {
                }
            }

            ControllerDescriptor controllerDescriptor = null;
            if (typeof(IController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            }
            else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
            }

//.........这里部分代码省略.........
开发者ID:JamesBurkett,项目名称:MvcSiteMapProvider,代码行数:101,代码来源:AuthorizeAttributeAclModule.cs

示例3: DisplayErrorPage

        /// <summary>
        /// Returns a response by executing the Error controller with the specified action.
        /// </summary>
        /// <param name="action">
        /// The action.
        /// </param>
        private void DisplayErrorPage(string action)
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", action);

            this.Server.ClearError();
            this.Response.Clear();

            var httpContext = new HttpContextWrapper(this.Context);
            var requestContext = new RequestContext(httpContext, routeData);

            IController errorController =
                ControllerBuilder.Current.GetControllerFactory().CreateController(
                    new RequestContext(
                        httpContext,
                        routeData),
                    "Error");

            // Clear the query string, in particular to avoid HttpRequestValidationException being re-raised
            // when the error view is rendered by the Error Controller.
            httpContext.RewritePath(httpContext.Request.FilePath, httpContext.Request.PathInfo, string.Empty);

            errorController.Execute(requestContext);
        }
开发者ID:jonhilt,项目名称:Who-Can-Help-Me,代码行数:31,代码来源:Global.asax.cs

示例4: context_BeginRequest

		/// <summary>
		/// Handles the Begin event of the request control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void context_BeginRequest(object sender, EventArgs e)
		{
			#region LoadApplicationRules Event

			if (Manager.ApplicationRulesNeedLoading)
			{
				// call load application rules
				var loadRulesArgs = new LoadRulesEventArgs();
				OnLoadApplicationRules(loadRulesArgs);

				Manager.LoadApplicationRules(loadRulesArgs);
			}

			#endregion

			var context = new HttpContextWrapper(((HttpApplication)sender).Context);
			var rewrittenUrl = Manager.RunRules(context);

			// make sure the rewrittenUrl returned is not null
			// a null value can indicate a proxy request
			if (rewrittenUrl != null)
			{
				// configure IIS7 for worker request
				// this will not do anything if the IIS7 worker request is not found
				Manager.ModifyIIS7WorkerRequest(context);

				// get the path and query for the rewritten URL
				string rewrittenUrlPath = rewrittenUrl.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped);

				// rewrite path using new URL
				if (HttpRuntime.UsingIntegratedPipeline && Manager.Configuration.Rewriter.AllowIis7TransferRequest)
				{
					var request = context.Request;
					var headers = new NameValueCollection(context.Request.Headers);

					int transferCount = 1;
					string transferCountHeader = headers["X-Rewriter-Transfer"];
					if (!String.IsNullOrEmpty(transferCountHeader) && Int32.TryParse(transferCountHeader, out transferCount))
						transferCount++;

					headers["X-Rewriter-Transfer"] = transferCount.ToString(CultureInfo.InvariantCulture); 

					context.Server.TransferRequest(
						rewrittenUrlPath,
						true,
						request.HttpMethod,
						headers
					);
				}
				else
					context.RewritePath(rewrittenUrlPath, Manager.Configuration.Rewriter.RebaseClientPath);
			}
		}
开发者ID:jsakamoto,项目名称:managedfusion-rewriter,代码行数:58,代码来源:RewriterModule.cs

示例5: context_PostMapRequestHandler

		/// <summary>
		/// Handles the PostMapRequestHandler event of the context control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void context_PostMapRequestHandler(object sender, EventArgs e)
		{
			var context = new HttpContextWrapper(((HttpApplication)sender).Context);

			// check to see if this is a proxy request
			if (context.Items.Contains(Manager.ProxyHandlerStorageName))
			{
				var proxy = context.Items[Manager.ProxyHandlerStorageName] as IHttpProxyHandler;

				context.RewritePath("~" + proxy.ResponseUrl.PathAndQuery);
				context.Handler = proxy;
			}
		}
开发者ID:jsakamoto,项目名称:managedfusion-rewriter,代码行数:18,代码来源:RewriterModule.cs

示例6: ProcessRequest

        public void ProcessRequest(HttpContext ctx)
        {
            var context = new HttpContextWrapper(ctx);

            // Handle invalid requests where HTML encoding is passed in the querystring.
            context.RewritePath(context.Server.HtmlDecode(context.Request.Url.PathAndQuery));

            if (context.Request.GetString("path") == string.Empty)
                throw new Exception("'path' must be specified in the querystring.");

            if (context.Request.GetInteger("width") == int.MinValue && context.Request.GetInteger("height") == int.MinValue)
                throw new Exception("'width' or 'height' must be specified in the querystring.");

            _path = context.Request.GetString("path");
            _extension = Path.GetExtension(_path).Replace("jpg", "jpeg").Trim('.');
            _width = context.Request.GetInteger("width");
            _height = context.Request.GetInteger("height");
            _quality = context.Request.GetInteger("quality", 100);
            _cache = context.Request.GetBoolean("cache", true);
            _cacheFile = string.Format("{0}\\_cache\\{1}", context.Server.MapPath(Path.GetDirectoryName(_path)), Path.GetFileName(_path).Replace(".", string.Format("_w{0}_h{1}_q{2}.", _width, (_height == int.MinValue) ? 0 : _height, _quality)));

            // Default flip to true if width is set, otherwise default it to false
            if (_width != int.MinValue)
                _flip = context.Request.GetBoolean("flip", true);
            else
                _flip = context.Request.GetBoolean("flip", false);

            if (_width > 1500 || _height > 1500)
                throw new Exception("The maximum resize dimensions for width/height is 1500 pixels.");

            //if (_cache && File.Exists(_cacheFile))
            //{
            //    context.Response.WriteFile(_cacheFile);
            //}

            if (!File.Exists(_cacheFile))
            {
                MemoryStream memoryStream = null;
                try
                {
                    memoryStream = File.Exists(context.Server.MapPath(_path)) ?
                        ImageTools.ResizeImage(context.Server.MapPath(_path), _width, _height, _quality, _flip, _extension) :
                        ImageTools.GetSpacer(1, 1, System.Drawing.Color.Transparent);

                    PathTools.EnsureDirectory(Path.GetDirectoryName(_cacheFile));
                    memoryStream.Save(_cacheFile);
                }
                catch (Exception)
                {

                }
                finally
                {
                    memoryStream.Close();
                }
            }

            var lastModified = File.GetLastWriteTime(_cacheFile);
            lastModified = new DateTime(lastModified.Year, lastModified.Month, lastModified.Day, lastModified.Hour, lastModified.Minute, lastModified.Second);  // Remove milliseconds from file datestamp

            if (!String.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]) && lastModified <= DateTime.Parse(context.Request.Headers["If-Modified-Since"]))
            {
                context.Response.StatusCode = 304;
                context.Response.StatusDescription = "Not Modified";
                context.Response.End();
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetLastModified(lastModified);
            context.Response.ContentType = "image/" + _extension;
            context.Response.WriteFile(_cacheFile);
            context.Response.End();
        }
开发者ID:wduffy,项目名称:Toltech.Mvc,代码行数:73,代码来源:ImageHandler.cs

示例7: OnBeginRequest

        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication) sender;
            HttpContextBase context = new HttpContextWrapper(app.Context);
            string path = context.Request.Path;

            //
            // Check to see if we are dealing with a request for the "elmah.axd" handler
            // and if so, we need to rewrite the path!
            //

            int handlerPosition = path.IndexOf(_handlerPathWithForwardSlash, StringComparison.OrdinalIgnoreCase);

            if (handlerPosition >= 0)
                context.RewritePath(
                    path.Substring(0, handlerPosition + _handlerPathLength),
                    path.Substring(handlerPosition + _handlerPathLength),
                    context.Request.QueryString.ToString());
        }
开发者ID:boena,项目名称:elmah-with-custom-data,代码行数:19,代码来源:FixIIS5xWildcardMappingModule.cs


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