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

C# Web.HttpContextWrapper类代码示例

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

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



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

示例1: ImportStylesheet

        /// <summary>
        /// Creates the proper CSS link reference within the target CSHTML page's head section
        /// </summary>
        /// <param name="virtualPath">The relative path of the image to be displayed, or its directory</param>
        /// <returns>Link tag if the file is found.</returns>
        public static ViewEngines.Razor.IHtmlString ImportStylesheet(string virtualPath)
        {
            ImageOptimizations.EnsureInitialized();

            if (Path.HasExtension(virtualPath))
                virtualPath = Path.GetDirectoryName(virtualPath);

            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var cssFileName = ImageOptimizations.LinkCompatibleCssFile(httpContext.Request.Browser) ?? ImageOptimizations.LowCompatibilityCssFileName;

            virtualPath = Path.Combine(virtualPath, cssFileName);
            var physicalPath = HttpContext.Current.Server.MapPath(virtualPath);

            if (File.Exists(physicalPath))
            {
                var htmlTag = new TagBuilder("link");
                htmlTag.MergeAttribute("href", ResolveUrl(virtualPath));
                htmlTag.MergeAttribute("rel", "stylesheet");
                htmlTag.MergeAttribute("type", "text/css");
                htmlTag.MergeAttribute("media", "all");

                return new NonEncodedHtmlString(htmlTag.ToString(TagRenderMode.SelfClosing));
            }

            return null;
        }
开发者ID:JefClaes,项目名称:Nancy.AspNetSprites.Razor,代码行数:31,代码来源:Sprite.cs


示例2: CreateController_WithRouteData_CreatesControllerInstance

        public void CreateController_WithRouteData_CreatesControllerInstance()
        {
            var context = new HttpContextWrapper(new HttpContext(
               new HttpRequest(null, "http://tempuri.org", null),
               new HttpResponse(null)));
            context.Items["CurrentResourcePackage"] = "test";

            var layoutTemplateBuilder = new LayoutRenderer();

            Controller dummyController = null;
            SystemManager.RunWithHttpContext(context, () =>
            {
                var routeData = new RouteData();
                routeData.Values.Add("controller", "dummy");
                dummyController = layoutTemplateBuilder.CreateController(routeData);
            });

            Assert.IsNotNull(dummyController);
            Assert.IsTrue(dummyController != null);
            Assert.IsTrue(dummyController.ControllerContext != null);
            Assert.IsTrue(dummyController.ControllerContext.RouteData != null);
            Assert.IsTrue(dummyController.ControllerContext.RouteData.Values != null);
            Assert.IsTrue(dummyController.ControllerContext.RouteData.Values.ContainsKey("controller"));
            Assert.IsTrue(dummyController.ControllerContext.RouteData.Values["controller"] != null);
            Assert.AreEqual<string>(dummyController.ControllerContext.RouteData.Values["controller"].ToString(), "dummy");
        }
开发者ID:vkoppaka,项目名称:feather,代码行数:26,代码来源:LayoutRendererTests.cs


示例3: InitHelpers

 public void InitHelpers()
 {
     var httpContext = new HttpContextWrapper(HttpContext.Current);
     var handler = httpContext.CurrentHandler as MvcHandler;
     if (handler == null)
         throw new InvalidOperationException("Unable to run template outside of ASP.NET MVC");
 }
开发者ID:OsirisTerje,项目名称:sonarlint-vs,代码行数:7,代码来源:MvcTemplateBase.cs


示例4: Application_Error

 protected void Application_Error()
 {
     var exception = Server.GetLastError();
     var httpException = exception as HttpException;
     Response.Clear();
     Server.ClearError();
     var routeData = new RouteData();
     routeData.Values["controller"] = "Errors";
     routeData.Values["action"] = "General";
     routeData.Values["exception"] = exception;
     Response.StatusCode = 500;
     if (httpException != null)
     {
         Response.StatusCode = httpException.GetHttpCode();
         switch (Response.StatusCode)
         {
             //case 403:
             //    routeData.Values["action"] = "Http403";
             //    break;
             case 404:
                 routeData.Values["action"] = "Http404";
                 break;
         }
     }
     // Avoid IIS7 getting in the middle
     Response.TrySkipIisCustomErrors = true;
     IController errorsController = new ErrorsController();
     HttpContextWrapper wrapper = new HttpContextWrapper(Context);
     var rc = new RequestContext(wrapper, routeData);
     errorsController.Execute(rc);
 }
开发者ID:LTHD,项目名称:WebBanHang,代码行数:31,代码来源:Global.asax.cs


示例5: ProcessUserAuthorizationAsync

		/// <summary>
		/// The process user authorization.
		/// </summary>
		/// <param name="context">The HTTP context.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// The response message.
		/// </returns>
		public Task<AccessTokenResponse> ProcessUserAuthorizationAsync(HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)) {
			if (context == null) {
				context = new HttpContextWrapper(HttpContext.Current);
			}

			return this.webConsumer.ProcessUserAuthorizationAsync(context.Request.Url, cancellationToken: cancellationToken);
		}
开发者ID:jiowei,项目名称:dotnetopenid,代码行数:15,代码来源:DotNetOpenAuthWebConsumer.cs


示例6: Application_Error

        protected void Application_Error()
        {
            var httpContext = HttpContext.Current;
            if (httpContext == null) return;

            var context = new HttpContextWrapper(System.Web.HttpContext.Current);
            var routeData = RouteTable.Routes.GetRouteData(context);

            var requestContext = new RequestContext(context, routeData);
            /* when the request is ajax the system can automatically handle a mistake with a JSON response. then overwrites the default response */
            if (requestContext.HttpContext.Request.IsAjaxRequest())
            {
                httpContext.Response.Clear();
                var controllerName = requestContext.RouteData.GetRequiredString("controller");
                var factory = ControllerBuilder.Current.GetControllerFactory();
                var controller = factory.CreateController(requestContext, controllerName);
                var controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

                var jsonResult = new JsonResult
                {
                    Data = new {success = false, serverError = "500"},
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                jsonResult.ExecuteResult(controllerContext);
                httpContext.Response.End();
            }
            else
            {
                httpContext.Response.Redirect("~/Error");
            }
        }
开发者ID:itverket,项目名称:geek-retreat,代码行数:31,代码来源:Global.asax.cs


示例7: ExecuteErrorPage

        private void ExecuteErrorPage()
        {
            ErrorInfo errorInfo = new ErrorInfo(httpStatusCode, this.exception, HttpContext.Current.Request);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", this.config.ErrorControllerName);
            routeData.Values.Add("action", this.config.ErrorActionName);
            routeData.Values.Add("errorInfo", errorInfo);

            HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            RequestContext requestContext = new RequestContext(httpContextWrapper, routeData);

            IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();
            IController errorController = controllerFactory.CreateController(requestContext, this.config.ErrorControllerName);

            errorController.Execute(requestContext);

            if (httpStatusCode > 0)
            {
                HttpContext.Current.Response.StatusCode = httpStatusCode;
                HttpContext.Current.Response.ContentType = "text/html";
            }

            HttpContext.Current.Response.TrySkipIisCustomErrors = true;
        }
开发者ID:mholec,项目名称:mvcexceptionhandler,代码行数:25,代码来源:MvcExceptionHandler.cs


示例8: DoPasswordProtect

        void DoPasswordProtect(HttpContextWrapper context)
        {
            var request = context.Request;
            var response = context.Response;

            //normally this would be some type of abstraction.
            var username = ConfigurationManager.AppSettings["br-username"];
            var password = ConfigurationManager.AppSettings["br-password"];

            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
            {
                var data = String.Format("{0}:{1}", username, password);
                var correctHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(data));

                string securityString = request.Headers["Authorization"];
                if (securityString == null)
                    goto forceRedirect;

                if (securityString != correctHeader)
                    goto forceRedirect;

                goto end;

            forceRedirect:
                var host = request.Url.Host.ToLower();
                response.AddHeader("WWW-Authenticate", String.Format(@"Basic realm=""{0}""", host));
                response.StatusCode = 401;
                response.End();
            end:
                ;
            }
        }
开发者ID:billrob,项目名称:billrob-web,代码行数:32,代码来源:PasswordProtectHttpModule.cs


示例9: For

        public string For(string controller, string action, IDictionary<string, object> values)
        {
            var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));

            return FullApplicationPath(httpContextWrapper.Request) + urlHelper.Action(action, controller, new RouteValueDictionary(values));
        }
开发者ID:pedrohso,项目名称:restfulie.net,代码行数:7,代码来源:AspNetMvcUrlGenerator.cs


示例10: GetMatches

        public IList<RouteData> GetMatches(string virtualPath)
        {

            HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
            
            return GetMatches(virtualPath, "GET", context);
        }
开发者ID:appliedi,项目名称:MerchantTribe,代码行数:7,代码来源:RouteEvaluator.cs


示例11: context_BeginRequest

        void context_BeginRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;

            var context = new HttpContextWrapper(application.Context);
            DoPasswordProtect(context);
        }
开发者ID:billrob,项目名称:billrob-web,代码行数:7,代码来源:PasswordProtectHttpModule.cs


示例12: Application_Error

 protected void Application_Error(object sender, EventArgs e)
 {
     var ex = Server.GetLastError();
     if (ex != null)
     {
         var bhEx = ex as FlhException;
         var context = new HttpContextWrapper(Context);
         var errorCode = bhEx == null ? ErrorCode.ServerError : bhEx.ErrorCode;
         var errorMsg = bhEx == null ? ex.ToString() : bhEx.Message;
         if (context.Request.IsAjaxRequest())
         {
             Context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new Web.JsonResultEntry
             {
                 Code = errorCode,
                 Message = errorMsg
             }));
         }
         else
         {
             IController ec = new Controllers.ErrorController();
             var routeData = new RouteData();
             routeData.Values["action"] = "index";
             routeData.Values["controller"] = "error";
             routeData.DataTokens["code"] = errorCode;
             routeData.DataTokens["msg"] = errorMsg;
             ec.Execute(new RequestContext(context, routeData));
         }
         Server.ClearError();
     }
 }
开发者ID:yeshusuper,项目名称:Flh,代码行数:30,代码来源:Global.asax.cs


示例13: RenderPartial

        private static void RenderPartial(string partialName, object model, TextWriter output)
        {
            //get a wrapper for the legacy WebForm context
            var httpCtx = new HttpContextWrapper(HttpContext.Current);

            //create a mock route that points to the empty controller
            var rt = new RouteData();
            rt.Values.Add("controller", "WebFormController");

            //create a controller context for the route and http context
            var ctx = new ControllerContext(
                new RequestContext(httpCtx, rt), new WebFormController());

            //find the partial view using the view-engine
            var view = ViewEngines.Engines.FindPartialView(ctx, partialName).View;

            //create a view context and assign the model
            var vctx = new ViewContext(ctx, view,
                new ViewDataDictionary { Model = model },
                new TempDataDictionary(),
                httpCtx.Response.Output);

            //render the partial view
            view.Render(vctx, output);
        }
开发者ID:joshrizzo,项目名称:MyLib,代码行数:25,代码来源:WebForms.cs


示例14: Application_AuthenticateRequest

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            var context = new HttpContextWrapper(HttpContext.Current);
            if (!string.IsNullOrEmpty(AuthSettings.EnableAuth) &&
                AuthSettings.EnableAuth.Equals(false.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                context.User = new TryWebsitesPrincipal(new TryWebsitesIdentity("[email protected]", null, "Local"));
                return;
            }

            if (!SecurityManager.TryAuthenticateSessionCookie(context))
            {
                if (SecurityManager.HasToken(context))
                {
                    // This is a login redirect
                    SecurityManager.AuthenticateRequest(context);
                    return;
                }

                var route = RouteTable.Routes.GetRouteData(context);
                // If the route is not registerd in the WebAPI RouteTable
                //      then it's not an API route, which means it's a resource (*.js, *.css, *.cshtml), not authenticated.
                // If the route doesn't have authenticated value assume true
                var isAuthenticated = route != null && (route.Values["authenticated"] == null || (bool)route.Values["authenticated"]);

                if (isAuthenticated)
                {
                    SecurityManager.AuthenticateRequest(context);
                }
                else if (context.IsBrowserRequest())
                {
                    SecurityManager.HandleAnonymousUser(context);
                }
            }
        }
开发者ID:davidlai-msft,项目名称:SimpleWAWS,代码行数:35,代码来源:Global.asax.cs


示例15: Application_Error

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception lastError = Server.GetLastError();
            Server.ClearError();

            int statusCode = 0;

            if (lastError.GetType() == typeof(HttpException))
            {
                statusCode = ((HttpException)lastError).GetHttpCode();
            }
            else
            {
                statusCode = 500;
            }

            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");
            routeData.Values.Add("statusCode", statusCode);
            routeData.Values.Add("exception", lastError);

            IController controller = new ErrorController();

            RequestContext requestContext = new RequestContext(contextWrapper, routeData);

            controller.Execute(requestContext);
            Response.End();
        }
开发者ID:StephanieMCraig,项目名称:personalsite,代码行数:31,代码来源:Global.asax.cs


示例16: Application_AuthenticateRequest

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            var context = new HttpContextWrapper(HttpContext.Current);

            if (!SecurityManager.TryAuthenticateRequest(context))
            {
                var route = RouteTable.Routes.GetRouteData(context);
                // If the route is not registerd in the WebAPI RouteTable
                //      then it's not an API route, which means it's a resource (*.js, *.css, *.cshtml), not authenticated.
                // If the route doesn't have authenticated value assume true
                var isAuthenticated = route != null && (route.Values["authenticated"] == null || (bool)route.Values["authenticated"]);
                var isFile = FileSystemHelpers.FileExists(HostingEnvironment.MapPath($"~{context.Request.Url.AbsolutePath.Replace('/', '\\')}"));

                if (isAuthenticated)
                {
                    context.Response.Headers["LoginUrl"] = SecurityManager.GetLoginUrl(context);
                    context.Response.StatusCode = 403; // Forbidden
                }
                else if (context.Request.Url.AbsolutePath.Equals("/api/health", StringComparison.OrdinalIgnoreCase))
                {
                    context.Response.WriteFile(HostingEnvironment.MapPath("~/health.html"));
                    context.Response.Flush();
                    context.Response.End();
                }
                else if (!isFile)
                {
                    context.Response.RedirectLocation = Environment.GetEnvironmentVariable("ACOM_MARKETING_PAGE") ?? $"{context.Request.Url.GetLeftPart(UriPartial.Authority)}/signin";
                    context.Response.StatusCode = 302;
                    context.Response.End();
                }
            }
        }
开发者ID:ConnorMcMahon,项目名称:AzureFunctionsPortal,代码行数:32,代码来源:Global.asax.cs


示例17: RenderSitecorePlaceHolder

        public static string RenderSitecorePlaceHolder(string key)
        {
            var sublayoutId = GetSublayoutIdFromPlaceHolder(Sitecore.Context.Item[Sitecore.FieldIDs.LayoutField], key);
            if (!string.IsNullOrEmpty(sublayoutId))
            {
                var layoutItem = Sitecore.Context.Database.GetItem(ID.Parse(sublayoutId));
                var controllerName = layoutItem.Fields["Controller"].Value;
                var actionName = layoutItem.Fields["Action"].Value;

                HttpContext.Current.RewritePath(string.Concat("/", controllerName, "/", actionName));

                RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
                if (routeData != null)
                {
                    var factory = new ControllerFactory();
                    var httpContextBase = new HttpContextWrapper(HttpContext.Current);
                    var context = new RequestContext(httpContextBase, routeData);
                    Type type = factory.GetController(context, controllerName);

                    if (type != null)
                    {
                        var controller = (Controller)factory.GetController(context, type);

                        var controllerContext = new ControllerContext(httpContextBase, routeData, controller);
                        var viewContext = new ViewContext(controllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null);

                        var helper = new HtmlHelper(viewContext, new ViewPage());

                        return helper.Action(actionName, controllerName).ToHtmlString();
                    }
                }
                HttpContext.Current.RewritePath("default.aspx");
            }
            return "";
        }
开发者ID:bplasmeijer,项目名称:SitecoreMVC,代码行数:35,代码来源:RazorControl.cs


示例18: Application_Error

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception lastError = Server.GetLastError();
            Server.ClearError();

            int statusCode = 0;

            if (lastError.GetType() == typeof(HttpException))
            {
                statusCode = ((HttpException) lastError).GetHttpCode();
            }
            else
            {
                // Not an HTTP related error so this is a problem in our code, set status to
                // 500 (internal server error)
                statusCode = 500;
            }

            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");
            routeData.Values.Add("statusCode", statusCode);
            routeData.Values.Add("exception", lastError);
            routeData.Values.Add("isAjaxRequet", contextWrapper.Request.IsAjaxRequest());

            IController controller = new ErrorController();

            RequestContext requestContext = new RequestContext(contextWrapper, routeData);

            controller.Execute(requestContext);
            Response.End();
        }
开发者ID:13daysaweek,项目名称:Mvc4CustomErrorPage,代码行数:34,代码来源:Global.asax.cs


示例19: HandleRequest

        /// <summary>
        /// Checks if any assigned filters validate the current handler, if so then assigns any filter
        /// that CanExecute to the response filter chain.
        /// 
        /// Checks if the request MIME type matches the list of mime types specified in the config,
        /// if it does, then it compresses it.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void HandleRequest(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            var http = new HttpContextWrapper(app.Context);

            //if debug is on, then don't compress
            if (!http.IsDebuggingEnabled)
            {
                //IMPORTANT: Compression must be assigned before any other filters are executed!
                // if compression is applied after the response has been modified then we will end
                // up getting encoding errors.
                // The compressor will not attempt to compress if the current filter is not ASP.Net's 
                // original filter. The filter could be changed by developers or perhaps even hosting
                // providers (based on their machine.config with their own modules.
                var c = new MimeTypeCompressor(new HttpContextWrapper(app.Context));
                c.AddCompression();
            }

            var filters = LoadFilters(http);

            if (ValidateCurrentHandler(filters))
            {
                ExecuteFilter(http, filters);
            }

            
        }
开发者ID:dufkaf,项目名称:ClientDependency,代码行数:36,代码来源:ClientDependencyModule.cs


示例20: AddBreadcrumb

        protected void AddBreadcrumb(string title, string targetAction, string targetController, RouteValueDictionary routeValues, int? index = null)
        {
            HttpContextWrapper httpContextWrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
            UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, new RouteData()));

            AddBreadcrumb(title, urlHelper.Action(targetAction, targetController, routeValues), index);
        }
开发者ID:revolutionaryarts,项目名称:wewillgather,代码行数:7,代码来源:BaseController.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Web.HttpCookie类代码示例发布时间:2022-05-26
下一篇:
C# Web.HttpContextBase类代码示例发布时间: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