當前位置: 首頁>>代碼示例>>C#>>正文


C# Web.HttpContextWrapper類代碼示例

本文整理匯總了C#中System.Web.HttpContextWrapper的典型用法代碼示例。如果您正苦於以下問題:C# HttpContextWrapper類的具體用法?C# HttpContextWrapper怎麽用?C# HttpContextWrapper使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpContextWrapper類屬於System.Web命名空間,在下文中一共展示了HttpContextWrapper類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的System.Web.HttpContextWrapper類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。