Example #1
0
        // This should be overridden and call a static method in Global.asax
        // (see https://docs.simpleinjector.org/en/latest/webformsintegration.html)
        protected virtual void InitializeHandler(IHttpHandler handler)
        {
            var handlerType = handler is Page?handler.GetType().BaseType : handler.GetType();

            var container = ContainerContextFactory.Current.GetContext().Container;

            container.GetRegistration(handlerType, true).Registration.InitializeInstance(handler);
        }
        public static void InitializeHandler(IHttpHandler handler)
        {
            var handlerType = handler is Page
                ? handler.GetType().BaseType
                : handler.GetType();

            if (handlerType == null)
            {
                return;
            }

            var instance = Container.GetRegistration(handlerType, true);

            instance?.Registration.InitializeInstance(handler);
        }
Example #3
0
        public HttpHandlerResult Run(IHttpHandler httpHandler, HttpFilterEvents eventType)
        {
            if (string.IsNullOrEmpty(FunctionName))
            {
                throw new ApplicationException("FunctionName is undefined!");
            }

            if (Events == HttpFilterEvents.None)
            {
                return(null);
            }
            if (!Events.HasFlag(eventType))
            {
                return(null);
            }

            if (Function != null)
            {
                return(Function.Invoke(httpHandler));
            }

            var method = httpHandler.GetType().GetMethod(FunctionName);

            if (method == null)
            {
                throw new ApplicationException($"HttpFilter method '{FunctionName}' not found!");
            }

            var @params = new object[] { httpHandler };

            return((HttpHandlerResult)method.Invoke(httpHandler, @params));
        }
        private static void Action(IHttpHandler httpHandler, TextWriter textWriter, bool arg3)
        {
            var handler = httpHandler as MvcHandler;

            if (handler == null)
            {
                var prop = httpHandler.GetType().GetProperty("InnerHandler",
                                                             BindingFlags.NonPublic | BindingFlags.Instance);
                if (prop != null)
                {
                    handler = prop.GetValue(httpHandler, null) as MvcHandler;
                }
            }
            if (handler != null)
            {
                var factory           = ControllerBuilder.Current.GetControllerFactory();
                var controllerName    = handler.RequestContext.RouteData.GetRequiredString("controller") + "Controller";
                var controller        = factory.CreateController(handler.RequestContext, controllerName) as Controller;
                var controllerContext = controller.Mock(x => x.ControllerContext);
                controllerContext.SetupGet(x => x.HttpContext).Returns(handler.RequestContext.HttpContext);
                controllerContext.SetupGet(x => x.RouteData).Returns(handler.RequestContext.RouteData);
                var previousOutput = controllerContext.Object.HttpContext.Response.Output;
                var response       = controllerContext.Mock(x => x.HttpContext.Response);
                response.Setup(x => x.Output).Returns(textWriter);
                var previousHttpContext = HttpContext.Current;
                controller.Invoke(handler.RequestContext.RouteData.GetRequiredString("action"));
                HttpContext.Current = previousHttpContext;
                response.Setup(x => x.Output).Returns(previousOutput);
            }
        }
Example #5
0
        void PostAcquireRequestState(object sender, EventArgs e)
        {
            // The PostAcquireRequestState event is raised after the session data has been obtained.
            // If the request is for a class that implements System.Web.UI.Page and it is a rest
            // method call, the WebServiceData class (that was explained in a previous post) is used
            // to call the requested method from the Page. After the method has been called,
            // the CompleteRequest method is called, bypassing all pipeline events and executing
            // the EndRequest method. This allows MS AJAX to be able to call a method on a page
            // instead of having to create a web service to call a method.
            HttpApplication app     = (HttpApplication)sender;
            HttpContext     context = app.Context;

            if (context == null)
            {
                return;
            }

            HttpRequest  request        = context.Request;
            string       contentType    = request.ContentType;
            IHttpHandler currentHandler = context.CurrentHandler;

            if (currentHandler == null)
            {
                return;
            }
            Type pageType = currentHandler.GetType();

            if (typeof(Page).IsAssignableFrom(pageType) && !String.IsNullOrEmpty(contentType) && contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                IHttpHandler h = RestHandler.GetHandler(context, pageType, request.FilePath);
                h.ProcessRequest(context);
                app.CompleteRequest();
            }
        }
Example #6
0
        public static void TrySetPageModel(HttpContext context)
        {
            if (context == null || context.Handler == null)
            {
                return;
            }

            IHttpHandler handler = context.Handler;

            // 判断当前处理器是否从MyPageView<TModel>继承过来
            Type handlerType = handler.GetType().BaseType;

            if (handlerType.IsGenericType &&
                handlerType.GetGenericTypeDefinition() == MyPageViewOpenType)
            {
                // 查找能响应这个请求的Action,并获取视图数据。
                InvokeInfo vkInfo = ReflectionHelper.GetActionInvokeInfo(context.Request.FilePath);
                if (vkInfo == null)
                {
                    return;
                }


                object model = ActionExecutor.ExecuteActionInternal(context, vkInfo);

                // 设置页面Model
                SetPageModel(context.Handler, model);
            }
        }
        protected void SetPropertyValue(IHttpHandler handler, object key, object value)
        {
            if (value == null)
            {
                return;
            }

            Type type = handler.GetType();

            PropertyInfo info =
                type.GetProperty(key.ToString(),
                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

            if (info == null || !info.CanWrite)
            {
                return;
            }

            if (!value.GetType().IsAssignableFrom(info.PropertyType))
            {
                return;
            }

            info.GetSetMethod().Invoke(handler, new object[] { value });
        }
        public void Test1()
        {
            InvokeInfo   invokeInfo1 = new InvokeInfo();
            IHttpHandler handler1    = ActionHandler.CreateHandler(invokeInfo1);

            Assert.AreEqual(typeof(ActionHandler), handler1.GetType());
        }
Example #9
0
        public static object ExecuteProcess(IHttpHandler handler)
        {
            ExceptionHelper.FalseThrow <ArgumentNullException>(handler != null, "handler");

            MethodInfo mi = GetMethodInfoByCurrentUri(handler.GetType());

            ExceptionHelper.FalseThrow(mi != null, "不能处理请求,无法从当前的Request找到匹配的ProcessRequest方法");

            return(mi.Invoke(handler, PrepareMethodParamValues(handler, mi)));
        }
        private void BuildUpPage(IHttpHandler page)
        {
            Container container = HttpContext.Current.Application[Container.CONTAINER] as Container;

            if (container == null)
            {
                throw new ApplicationException("Container in application context is null.");
            }

            container.BuildUp(page, page.GetType().BaseType);
        }
Example #11
0
 private static IHttpHandler Build(IHttpHandler page)
 {
     try
     {
         return(unityContainer.BuildUp(page.GetType().BaseType, page) as IHttpHandler);
     }
     catch (Exception)
     {
         return(page);
     }
 }
Example #12
0
        private static bool PageUsesInjection(IHttpHandler handler)
        {
            if (handler == null)
            {
                return(false);
            }

            var attributes = handler.GetType().GetCustomAttributes(typeof(UsesInjectionAttribute), true);

            return(attributes.Length > 0);
        }
Example #13
0
        public void Test2()
        {
            InvokeInfo invokeInfo2 = new InvokeInfo();

            invokeInfo2.Action = new ActionDescription(typeof(ActionHandlerTest).GetMethod("Test1"));
            invokeInfo2.Action.GetType().SetValue("SessionMode",
                                                  invokeInfo2.Action, new SessionModeAttribute(SessionMode.Support));

            IHttpHandler handler2 = ActionHandler.CreateHandler(invokeInfo2);

            Assert.AreEqual(typeof(RequiresSessionActionHandler), handler2.GetType());
        }
Example #14
0
        /// <summary>
        /// 当前请求处理的handler
        /// </summary>
        /// <returns></returns>
        public ViewResult Handler()
        {
            IHttpHandler handler = base.HttpContext.Handler;

            //IHttpHandlerFactory

            //MvcHandler
            //MvcRouteHandler
            ViewBag.HandlerName = handler.GetType().ToString();
            ViewBag.Url         = Request.Url.AbsoluteUri;
            return(View());
        }
 public string Sniff(IHttpHandler handler)
 {
 	if (handler == null) 
 	{
 		return string.Empty;
 	}
     WorkSpaceInfo wsi = (WorkSpaceInfo) Attribute.GetCustomAttribute(handler.GetType(), typeof (WorkSpaceInfo));
     if (wsi != null)
     {
         return wsi.WorkSpaceName;
     }
     return string.Empty;
 }
Example #16
0
        internal async Task <HttpHandlerResult> ExecuteAsync(IHttpHandler handlerObj, CancellationToken token)
        {
            var method = handlerObj.HttpContext.Request.HttpMethod;
            HttpHandlerResult result = null;

            var filters = handlerObj.GetType().GetCustomAttributes()
                          .OfType <HttpFilterAttribute>().ToArray();

            foreach (var filter in filters)
            {
                result = filter.Run(handlerObj, HttpFilterEvents.Before);
                if (result != null)
                {
                    return(result);
                }
            }

            try {
                if (handlerObj is HttpHandlerAsync handlerAsync)
                {
                    if (!execMapAsync.TryGetValue(method, out var execFunc))
                    {
                        throw new ApplicationException($"Unsupported method '{method}'!");
                    }

                    result = await execFunc.Invoke(handlerAsync, token);
                }
                else if (handlerObj is HttpHandler handler)
                {
                    if (!execMap.TryGetValue(method, out var execFunc))
                    {
                        throw new ApplicationException($"Unsupported method '{method}'!");
                    }

                    result = await Task.Run(() => execFunc.Invoke(handler), token);
                }
            }
            finally {
                foreach (var filter in filters)
                {
                    var newResult = filter.RunAfter(handlerObj, result);
                    if (newResult != null)
                    {
                        result = newResult;
                        break;
                    }
                }
            }

            return(result);
        }
Example #17
0
        public void Test3()
        {
            InvokeInfo invokeInfo3 = new InvokeInfo();

            invokeInfo3.Controller = new ControllerDescription(typeof(ActionHandlerTest));
            invokeInfo3.Controller.GetType().SetValue("SessionMode",
                                                      invokeInfo3.Controller, new SessionModeAttribute(SessionMode.ReadOnly));

            IHttpHandler handler3 = ActionHandler.CreateHandler(invokeInfo3);

            Assert.AreEqual(typeof(ReadOnlySessionActionHandler), handler3.GetType());

            Assert.AreEqual(false, handler3.IsReusable);
        }
Example #18
0
        private static void OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            IHttpHandler handler = HttpContext.Current.Handler;

            HttpContext.Current.Application.GetContainer().BuildUp(handler.GetType(), handler);

            // User Controls are ready to be built up after the page initialization is complete
            Page page = HttpContext.Current.Handler as Page;

            if (page != null)
            {
                page.InitComplete += OnPageInitComplete;
            }
        }
Example #19
0
        public string Sniff(IHttpHandler handler)
        {
            if (handler == null)
            {
                return(string.Empty);
            }
            WorkSpaceInfo wsi = (WorkSpaceInfo)Attribute.GetCustomAttribute(handler.GetType(), typeof(WorkSpaceInfo));

            if (wsi != null)
            {
                return(wsi.WorkSpaceName);
            }
            return(string.Empty);
        }
Example #20
0
        /// <summary>在页面查找指定ID的控件,采用反射字段的方法,避免遍历Controls引起子控件构造</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T FindControlInPage <T>(String id) where T : Control
        {
            if (HttpContext.Current == null)
            {
                return(null);
            }

            IHttpHandler handler = HttpContext.Current.Handler;

            if (handler == null)
            {
                return(null);
            }

            FieldInfoX fix = null;

            if (!String.IsNullOrEmpty(id))
            {
                fix = FieldInfoX.Create(handler.GetType(), id);
            }
            else
            {
                Type      t  = typeof(T);
                FieldInfo fi = handler.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(item => item.FieldType == t);
                if (fi != null)
                {
                    fix = FieldInfoX.Create(fi);
                }
            }

            if (fix == null)
            {
                return(null);
            }

            return(fix.GetValue(handler) as T);
        }
Example #21
0
 public void Init(HttpApplication context)
 {
     context.PreRequestHandlerExecute += (sender, e) =>
     {
         IHttpHandler handler = context.Context.CurrentHandler;
         if (handler != null)
         {
             var name = handler.GetType().Assembly.FullName;
             if (!name.StartsWith("System.Web") && !name.StartsWith("Microsoft"))
             {
                 InitializeHandler(handler);
             }
         }
     };
 }
        /// <summary>
        /// Evaluate handler condition
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public bool Evaluate(ConditionArgs args)
        {
            bool isMatch = false;

            IHttpHandler handler = (HttpContext.Current != null ?
                                    HttpContext.Current.CurrentHandler :
                                    null);

            if (handler != null && _handlerType != null)
            {
                isMatch = handler.GetType().Equals(_handlerType);
            }

            return(isMatch);
        }
Example #23
0
        protected void Application_PostMapRequestHandler(object sender, EventArgs e)
        {
            IHttpHandler handler = this.Request.RequestContext.HttpContext.CurrentHandler;
            var          attrs   = handler.GetType().GetCustomAttributes(typeof(AuthorizationAttribute), true);

            if (attrs.Length > 0)
            {
                var code  = (attrs[0] as AuthorizationAttribute).AuthCode;
                var token = this.Request.Params.Get("token");
                try
                {
                    //给接口发送请求
                    var postData     = "token=" + token;
                    var delRpturl    = host + this.Server.HtmlEncode(string.Format("/auth/{0}?{1}", code, postData));
                    var proxyRequest = (HttpWebRequest)WebRequest.Create(delRpturl);
                    proxyRequest.Method        = "Post";
                    proxyRequest.UserAgent     = this.Request.UserAgent;
                    proxyRequest.ContentType   = "application/x-www-form-urlencoded";
                    proxyRequest.ContentLength = 0;
                    var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                    proxyRequest.CachePolicy = noCachePolicy;
                    //发出代理请求,并获取响应
                    using (HttpWebResponse proxyResponse = proxyRequest.GetResponse() as HttpWebResponse)
                    {
                        string Result;
                        using (Stream receiveStream = proxyResponse.GetResponseStream())
                        {
                            Encoding     Encode     = Encoding.GetEncoding("utf-8");
                            StreamReader readStream = new StreamReader(receiveStream, Encode);
                            Result = readStream.ReadToEnd();
                        }
                        proxyResponse.Close();
                        if (Result == "false")
                        {
                            this.Context.Response.ContentType = "text/html";
                            this.Response.StatusCode          = 202;
                            this.Response.Write(405);
                            this.Response.End();
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// Checks whether or not handler is a transfer handler.
        /// </summary>
        /// <param name="handler">An instance of handler to validate.</param>
        /// <returns>True if handler is a transfer handler, otherwise - False.</returns>
        private bool IsHandlerToFilter(IHttpHandler handler)
        {
            if (handler != null)
            {
                var handlerName = handler.GetType().FullName;
                foreach (var h in this.handlersToFilter.Select(t => t.Value))
                {
                    if (string.Equals(handlerName, h, StringComparison.Ordinal))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Example #25
0
        protected override object Evaluate(HttpContext context, Control control)
        {
            if ((context == null) || (string.Empty.Equals(PropertyName)))
            {
                return(null);
            }
            IHttpHandler handler  = context.Handler;
            Type         type     = handler.GetType();
            PropertyInfo property = type.GetProperty(PropertyName);

            if (property == null)
            {
                return(null);
            }
            return(property.GetValue(handler, null));
        }
        /// <summary>
        /// Checks whether or not handler is a transfer handler.
        /// </summary>
        /// <param name="handler">An instance of handler to validate.</param>
        /// <returns>True if handler is a transfer handler, otherwise - False.</returns>
        private bool IsHandlerToFilter(IHttpHandler handler)
        {
            if (handler != null)
            {
                var handlerName = handler.GetType().FullName;
                foreach (var h in this.handlersToFilter.Select(t => t.Value))
                {
                    if (string.Equals(handlerName, h, StringComparison.Ordinal))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #27
0
        public ViewResult MVCHandler()
        {
            //System.Web.Routing.UrlRoutingModule
            List <string> processList = new List <string>();

            processList.Add(string.Format("1 请求已经生成HttpApplication,经过一系列的Module处理后"));

            RouteData routeData = base.RouteData;

            processList.Add(string.Format("2 请求到达Module:{0},该模块会解析当前的请求,找到当前请求的{1}", typeof(UrlRoutingModule), routeData.GetType().Name));
            processList.Add(string.Format("3 该RouteData的内容为{0},", JsonHelper.ToJson <RouteData>(routeData)));
            //IHttpHandler handler = routeData.RouteHandler.GetHttpHandler(base.Request.RequestContext);//当前请求信息为参数
            //这里会抛异常  Additional information: 只能在引发“HttpApplication.AcquireRequestState”之前调用“HttpContext.SetSessionStateBehavior”。
            //这个时候handler已经明确了,不能再次获取了
            IHttpHandler handler = base.HttpContext.Handler;

            processList.Add(string.Format("4 然后调用该RouteData.RouteHandler.GetHttpHandler去获取该请求的处理handler:{0}", handler.GetType().FullName));
            processList.Add(string.Format("5 该handler默认是{0},这个IHttpHandler会根据this.RequestContext.RouteData的控制器信息去找控制器的工厂,也就是我们扩展的{1},通过反射来完成控制器的激活 ",
                                          handler.GetType().FullName, typeof(UnityControllerFactory)));

            /*
             * public class MvcHandler : IHttpHandler
             * {
             *   public bool IsReusable
             *   {
             *       get { return false; }
             *   }
             *   public RequestContext RequestContext { get; private set; }
             *   public MvcHandler(RequestContext requestContext)
             *   {
             *       this.RequestContext = requestContext;
             *   }
             *   public void ProcessRequest(HttpContext context)
             *   {
             *       string controllerName = this.RequestContext.RouteData.Controller;
             *       IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();
             *       IController controller = controllerFactory.CreateController(this.RequestContext, controllerName);
             *       controller.Execute(this.RequestContext);
             *   }
             * }
             */

            //UrlRoutingModule
            //RouteHandler
            //System.Web.Mvc.MvcHandler
            return(View(processList));
        }
Example #28
0
        /// <summary>
        /// Checks whether or not handler is a transfer handler.
        /// </summary>
        /// <param name="handler">An instance of handler to validate.</param>
        /// <returns>True if handler is a transfer handler, otherwise - False.</returns>
        private bool IsHandlerToFilter(IHttpHandler handler)
        {
            if (handler != null)
            {
                var handlerName = handler.GetType().FullName;
                foreach (var h in this.Handlers)
                {
                    if (string.Equals(handlerName, h, StringComparison.Ordinal))
                    {
                        WebEventSource.Log.WebRequestFilteredOutByRequestHandler();
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #29
0
        public void ConfigureSessionState_ReadOnly_ChangesHandler()
        {
            // Arrange
            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.SetupProperty(o => o.Handler);
            HttpContextBase httpContext = mockHttpContext.Object;

            DynamicSessionStateConfigurator35 configurator = new DynamicSessionStateConfigurator35(httpContext);

            // Act
            configurator.ConfigureSessionState(ControllerSessionState.ReadOnly);
            IHttpHandler newHandler = httpContext.Handler;

            // Assert
            Assert.AreEqual(typeof(MvcReadOnlySessionHandler), newHandler.GetType());
        }
        /// <summary>
        /// Internal for testability outside of a web application.
        /// </summary>
        /// <param name="handler"></param>
        /// <returns>The injection behaviour.</returns>
        protected internal IInjectionBehaviour GetInjectionBehaviour(IHttpHandler handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }

            if (handler is DefaultHttpHandler)
            {
                return(_noInjection);
            }
            else
            {
                var handlerType = handler.GetType();
                return(GetInjectionBehaviourForHandlerType(handlerType));
            }
        }
        /// <summary>
        /// Map request handler to context
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnPostMapRequestHandler(object sender, EventArgs e)
        {
            HttpContext  context = ((HttpApplication)sender).Context;
            IHttpHandler handler = context.CurrentHandler;

            if (handler != null)
            {
                lock (_handlersLock) {
                    // Get code behind type
                    Type handlerType = handler.GetType();

                    // If handler not known map to context
                    if (!_handlerTypes.Contains(handlerType))
                    {
                        MapHandlerContext(handlerType);
                        _handlerTypes.Add(handlerType);
                    }
                }
            }
        }
Example #32
0
        private static Assembly GetWebApplicationAssembly(HttpContext context)
        {
            ChoGuard.ArgumentNotNull(context, "context");

            IHttpHandler handler = context.CurrentHandler;

            if (handler == null)
            {
                return(null);
            }

            Type type = handler.GetType();

            while (type != null && type != typeof(object) && type.Namespace == AspNetNamespace)
            {
                type = type.BaseType;
            }

            return(type.Assembly);
        }
 private void ExecuteInternal(IHttpHandler handler, TextWriter writer, bool preserveForm, bool setPreviousPage, VirtualPath path, VirtualPath filePath, string physPath, Exception error, string queryStringOverride)
 {
     if (handler == null)
     {
         throw new ArgumentNullException("handler");
     }
     HttpRequest request = this._context.Request;
     HttpResponse response = this._context.Response;
     HttpApplication applicationInstance = this._context.ApplicationInstance;
     HttpValueCollection form = null;
     VirtualPath path2 = null;
     string queryStringText = null;
     TextWriter writer2 = null;
     AspNetSynchronizationContext syncContext = null;
     this.VerifyTransactionFlow(handler);
     this._context.PushTraceContext();
     this._context.SetCurrentHandler(handler);
     bool enabled = this._context.SyncContext.Enabled;
     this._context.SyncContext.Disable();
     try
     {
         try
         {
             this._context.ServerExecuteDepth++;
             path2 = request.SwitchCurrentExecutionFilePath(filePath);
             if (!preserveForm)
             {
                 form = request.SwitchForm(new HttpValueCollection());
                 if (queryStringOverride == null)
                 {
                     queryStringOverride = string.Empty;
                 }
             }
             if (queryStringOverride != null)
             {
                 queryStringText = request.QueryStringText;
                 request.QueryStringText = queryStringOverride;
             }
             if (writer != null)
             {
                 writer2 = response.SwitchWriter(writer);
             }
             Page page = handler as Page;
             if (page != null)
             {
                 if (setPreviousPage)
                 {
                     page.SetPreviousPage(this._context.PreviousHandler as Page);
                 }
                 Page page2 = this._context.Handler as Page;
                 if ((page2 != null) && page2.SmartNavigation)
                 {
                     page.SmartNavigation = true;
                 }
                 if (page is IHttpAsyncHandler)
                 {
                     syncContext = this._context.InstallNewAspNetSynchronizationContext();
                 }
             }
             if (((handler is StaticFileHandler) || (handler is DefaultHttpHandler)) && !DefaultHttpHandler.IsClassicAspRequest(filePath.VirtualPathString))
             {
                 try
                 {
                     response.WriteFile(physPath);
                 }
                 catch
                 {
                     error = new HttpException(0x194, string.Empty);
                 }
             }
             else if (!(handler is Page))
             {
                 error = new HttpException(0x194, string.Empty);
             }
             else
             {
                 if (handler is IHttpAsyncHandler)
                 {
                     bool isInCancellablePeriod = this._context.IsInCancellablePeriod;
                     if (isInCancellablePeriod)
                     {
                         this._context.EndCancellablePeriod();
                     }
                     try
                     {
                         IHttpAsyncHandler handler2 = (IHttpAsyncHandler) handler;
                         IAsyncResult result = handler2.BeginProcessRequest(this._context, null, null);
                         if (!result.IsCompleted)
                         {
                             bool flag3 = false;
                             try
                             {
                                 try
                                 {
                                 }
                                 finally
                                 {
                                     Monitor.Exit(applicationInstance);
                                     flag3 = true;
                                 }
                                 WaitHandle asyncWaitHandle = result.AsyncWaitHandle;
                                 if (asyncWaitHandle == null)
                                 {
                                     goto Label_0210;
                                 }
                                 asyncWaitHandle.WaitOne();
                                 goto Label_0226;
                             Label_020A:
                                 Thread.Sleep(1);
                             Label_0210:
                                 if (!result.IsCompleted)
                                 {
                                     goto Label_020A;
                                 }
                             }
                             finally
                             {
                                 if (flag3)
                                 {
                                     Monitor.Enter(applicationInstance);
                                 }
                             }
                         }
                     Label_0226:
                         try
                         {
                             handler2.EndProcessRequest(result);
                         }
                         catch (Exception exception)
                         {
                             error = exception;
                         }
                         goto Label_0306;
                     }
                     finally
                     {
                         if (isInCancellablePeriod)
                         {
                             this._context.BeginCancellablePeriod();
                         }
                     }
                 }
                 using (new DisposableHttpContextWrapper(this._context))
                 {
                     try
                     {
                         handler.ProcessRequest(this._context);
                     }
                     catch (Exception exception2)
                     {
                         error = exception2;
                     }
                 }
             }
         }
         finally
         {
             this._context.ServerExecuteDepth--;
             this._context.RestoreCurrentHandler();
             if (writer2 != null)
             {
                 response.SwitchWriter(writer2);
             }
             if ((queryStringOverride != null) && (queryStringText != null))
             {
                 request.QueryStringText = queryStringText;
             }
             if (form != null)
             {
                 request.SwitchForm(form);
             }
             request.SwitchCurrentExecutionFilePath(path2);
             if (syncContext != null)
             {
                 this._context.RestoreSavedAspNetSynchronizationContext(syncContext);
             }
             if (enabled)
             {
                 this._context.SyncContext.Enable();
             }
             this._context.PopTraceContext();
         }
     }
     catch
     {
         throw;
     }
 Label_0306:
     if (error == null)
     {
         return;
     }
     if ((error is HttpException) && (((HttpException) error).GetHttpCode() != 500))
     {
         error = null;
     }
     if (path != null)
     {
         throw new HttpException(System.Web.SR.GetString("Error_executing_child_request_for_path", new object[] { path }), error);
     }
     throw new HttpException(System.Web.SR.GetString("Error_executing_child_request_for_handler", new object[] { handler.GetType().ToString() }), error);
 }
		private void SetPropertyValue(IHttpHandler handler, object key, object value)
		{
			if (value == null) return;

			String name = key.ToString();
			Type type = handler.GetType();
			Type valueType = value.GetType();
		
			FieldInfo fieldInfo = type.GetField(name, PropertyBindingFlags);

			if (fieldInfo != null)
			{
				if (fieldInfo.FieldType.IsAssignableFrom(valueType))
				{
					fieldInfo.SetValue(handler, value);
				}
			}
			else
			{
				PropertyInfo propInfo = type.GetProperty(name, PropertyBindingFlags);

				if (propInfo != null && (propInfo.CanWrite &&
					(propInfo.PropertyType.IsAssignableFrom(valueType))))
				{
					propInfo.GetSetMethod().Invoke(handler, new object[] { value });
				}
			}
		}
 public void RemapHandler(IHttpHandler handler)
 {
     IIS7WorkerRequest request = this._wr as IIS7WorkerRequest;
     if (request != null)
     {
         if (this._notificationContext.CurrentNotification >= RequestNotification.MapRequestHandler)
         {
             throw new InvalidOperationException(System.Web.SR.GetString("Invoke_before_pipeline_event", new object[] { "HttpContext.RemapHandler", "HttpApplication.MapRequestHandler" }));
         }
         string handlerType = null;
         string handlerName = null;
         if (handler != null)
         {
             Type type = handler.GetType();
             handlerType = type.AssemblyQualifiedName;
             handlerName = type.FullName;
         }
         request.SetRemapHandler(handlerType, handlerName);
     }
     this._remapHandler = handler;
 }
 public override void Execute(IHttpHandler handler, System.IO.TextWriter writer, bool preserveForm)
 {
     var requestContext = ((System.Web.Mvc.MvcHandler)handler.GetType().GetField("_httpHandler", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(handler)).RequestContext;
     writer.Write(requestContext.RouteData.Values.ToQueryString());
 }
        /// <summary>
        /// Checks whether or not handler is a transfer handler.
        /// </summary>
        /// <param name="handler">An instance of handler to validate.</param>
        /// <returns>True if handler is a transfer handler, otherwise - False.</returns>
        private bool IsHandlerToFilter(IHttpHandler handler)
        {
            if (handler != null)
            {
                var handlerName = handler.GetType().FullName;
                foreach (var h in this.Handlers)
                {
                    if (string.Equals(handlerName, h, StringComparison.Ordinal))
                    {
                        WebEventSource.Log.WebRequestFilteredOutByRequestHandler();
                        return true;
                    }
                }
            }

            return false;
        }
Example #38
0
        /// <devdoc>
        ///    <para>
        ///       Set custom mapping handler processing the request <see cref='System.Web.IHttpHandler'/>
        ///    </para>
        /// </devdoc>
        public void RemapHandler(IHttpHandler handler) {
            EnsureHasNotTransitionedToWebSocket();

            IIS7WorkerRequest wr = _wr as IIS7WorkerRequest;

            if (wr != null) {
                // Remap handler not allowed after ResolveRequestCache notification
                if (_notificationContext.CurrentNotification >= RequestNotification.MapRequestHandler) {
                    throw new InvalidOperationException(SR.GetString(SR.Invoke_before_pipeline_event, "HttpContext.RemapHandler", "HttpApplication.MapRequestHandler"));
                }

                string handlerTypeName = null;
                string handlerName = null;

                if (handler != null) {
                    Type handlerType = handler.GetType();

                    handlerTypeName = handlerType.AssemblyQualifiedName;
                    handlerName = handlerType.FullName;
                }

                wr.SetRemapHandler(handlerTypeName, handlerName);
            }

            _remapHandler = handler;
        }
        /// <summary>
        /// Internal for testability outside of a web application.
        /// </summary>
        /// <param name="handler"></param>
        /// <returns>The injection behavior.</returns>
        protected internal IInjectionBehavior GetInjectionBehavior(IHttpHandler handler)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            if (handler is DefaultHttpHandler)
            {
                return _noInjection;
            }
            else
            {
                var handlerType = handler.GetType();
                return GetInjectionBehaviorForHandlerType(handlerType);
            }
        }
Example #40
0
        private void ExecuteInternal(IHttpHandler handler, TextWriter writer, bool preserveForm, bool setPreviousPage,
            VirtualPath path, VirtualPath filePath, string physPath, Exception error, string queryStringOverride) {

            EnsureHasNotTransitionedToWebSocket();

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

            HttpRequest request = _context.Request;
            HttpResponse response = _context.Response;
            HttpApplication app = _context.ApplicationInstance;

            HttpValueCollection savedForm = null;
            VirtualPath savedCurrentExecutionFilePath = null;
            string savedQueryString = null;
            TextWriter savedOutputWriter = null;
            AspNetSynchronizationContextBase savedSyncContext = null;

            // Transaction wouldn't flow into ASPCOMPAT mode -- need to report an error
            VerifyTransactionFlow(handler);

            // create new trace context
            _context.PushTraceContext();

            // set the new handler as the current handler
            _context.SetCurrentHandler(handler);

            // because we call this synchrnously async operations must be disabled
            bool originalSyncContextWasEnabled = _context.SyncContext.Enabled;
            _context.SyncContext.Disable();

            // Execute the handler
            try {
                try {
                    _context.ServerExecuteDepth++;

                    savedCurrentExecutionFilePath = request.SwitchCurrentExecutionFilePath(filePath);

                    if (!preserveForm) {
                        savedForm = request.SwitchForm(new HttpValueCollection());

                        // Clear out the query string, but honor overrides
                        if (queryStringOverride == null)
                            queryStringOverride = String.Empty;
                    }

                    // override query string if requested
                    if (queryStringOverride != null) {
                        savedQueryString = request.QueryStringText;
                        request.QueryStringText = queryStringOverride;
                    }

                    // capture output if requested
                    if (writer != null)
                        savedOutputWriter = response.SwitchWriter(writer);

                    Page targetPage = handler as Page;
                    if (targetPage != null) {
                        if (setPreviousPage) {
                            // Set the previousPage of the new Page as the previous Page
                            targetPage.SetPreviousPage(_context.PreviousHandler as Page);
                        }

                        Page sourcePage = _context.Handler as Page;

#pragma warning disable 0618    // To avoid deprecation warning
                        // If the source page of the transfer has smart nav on,
                        // always do as if the destination has it too (ASURT 97732)
                        if (sourcePage != null && sourcePage.SmartNavigation)
                            targetPage.SmartNavigation = true;
#pragma warning restore 0618

                        // If the target page is async need to save/restore sync context
                        if (targetPage is IHttpAsyncHandler) {
                            savedSyncContext = _context.InstallNewAspNetSynchronizationContext();
                        }
                    }

                    if ((handler is StaticFileHandler || handler is DefaultHttpHandler) &&
                       !DefaultHttpHandler.IsClassicAspRequest(filePath.VirtualPathString)) {
                        // cannot apply static files handler directly
                        // -- it would dump the source of the current page
                        // instead just dump the file content into response
                        try {
                            response.WriteFile(physPath);
                        }
                        catch {
                            // hide the real error as it could be misleading
                            // in case of mismapped requests like /foo.asmx/bar
                            error = new HttpException(404, String.Empty);
                        }
                    }
                    else if (!(handler is Page)) {
                        // disallow anything but pages
                        error = new HttpException(404, String.Empty);
                    }
                    else if (handler is IHttpAsyncHandler) {
                        // Asynchronous handler

                        // suspend cancellable period (don't abort this thread while
                        // we wait for another to finish)
                        bool isCancellable =  _context.IsInCancellablePeriod;
                        if (isCancellable)
                            _context.EndCancellablePeriod();

                        try {
                            IHttpAsyncHandler asyncHandler = (IHttpAsyncHandler)handler;

                            if (!AppSettings.UseTaskFriendlySynchronizationContext) {
                                // Legacy code path: behavior ASP.NET <= 4.0

                                IAsyncResult ar = asyncHandler.BeginProcessRequest(_context, null, null);

                                // wait for completion
                                if (!ar.IsCompleted) {
                                    // suspend app lock while waiting
                                    bool needToRelock = false;

                                    try {
                                        try { }
                                        finally {
                                            _context.SyncContext.DisassociateFromCurrentThread();
                                            needToRelock = true;
                                        }

                                        WaitHandle h = ar.AsyncWaitHandle;

                                        if (h != null) {
                                            h.WaitOne();
                                        }
                                        else {
                                            while (!ar.IsCompleted)
                                                Thread.Sleep(1);
                                        }
                                    }
                                    finally {
                                        if (needToRelock) {
                                            _context.SyncContext.AssociateWithCurrentThread();
                                        }
                                    }
                                }

                                // end the async operation (get error if any)

                                try {
                                    asyncHandler.EndProcessRequest(ar);
                                }
                                catch (Exception e) {
                                    error = e;
                                }
                            }
                            else {
                                // New code path: behavior ASP.NET >= 4.5
                                IAsyncResult ar;
                                bool blockedThread;

                                using (CountdownEvent countdownEvent = new CountdownEvent(1)) {
                                    using (_context.SyncContext.AcquireThreadLock()) {
                                        // Kick off the asynchronous operation
                                        ar = asyncHandler.BeginProcessRequest(_context,
                                           cb: _ => { countdownEvent.Signal(); },
                                           extraData: null);
                                    }

                                    // The callback passed to BeginProcessRequest will signal the CountdownEvent.
                                    // The Wait() method blocks until the callback executes; no-ops if the operation completed synchronously.
                                    blockedThread = !countdownEvent.IsSet;
                                    countdownEvent.Wait();
                                }

                                // end the async operation (get error if any)

                                try {
                                    using (_context.SyncContext.AcquireThreadLock()) {
                                        asyncHandler.EndProcessRequest(ar);
                                    }

                                    // If we blocked the thread, YSOD the request to display a diagnostic message.
                                    if (blockedThread && !_context.SyncContext.AllowAsyncDuringSyncStages) {
                                        throw new InvalidOperationException(SR.GetString(SR.Server_execute_blocked_on_async_handler));
                                    }
                                }
                                catch (Exception e) {
                                    error = e;
                                }
                            }
                        }
                        finally {
                            // resume cancelleable period
                            if (isCancellable)
                                _context.BeginCancellablePeriod();
                        }
                    }
                    else {
                        // Synchronous handler

                        using (new DisposableHttpContextWrapper(_context)) {
                            try {
                                handler.ProcessRequest(_context);
                            }
                            catch (Exception e) {
                                error = e;
                            }
                        }
                    }
                }
                finally {
                    _context.ServerExecuteDepth--;

                    // Restore the handlers;
                    _context.RestoreCurrentHandler();

                    // restore output writer
                    if (savedOutputWriter != null)
                        response.SwitchWriter(savedOutputWriter);

                    // restore overriden query string
                    if (queryStringOverride != null && savedQueryString != null)
                        request.QueryStringText = savedQueryString;

                    if (savedForm != null)
                        request.SwitchForm(savedForm);

                    request.SwitchCurrentExecutionFilePath(savedCurrentExecutionFilePath);

                    if (savedSyncContext != null) {
                        _context.RestoreSavedAspNetSynchronizationContext(savedSyncContext);
                    }

                    if (originalSyncContextWasEnabled) {
                        _context.SyncContext.Enable();
                    }

                    // restore trace context
                    _context.PopTraceContext();
                }
            }
            catch { // Protect against exception filters
                throw;
            }

            // Report any error
            if (error != null) {
                // suppress errors with HTTP codes (for child requests they mislead more than help)
                if (error is HttpException && ((HttpException)error).GetHttpCode() != 500)
                    error = null;

                if (path != null)
                    throw new HttpException(SR.GetString(SR.Error_executing_child_request_for_path, path), error);

                throw new HttpException(SR.GetString(SR.Error_executing_child_request_for_handler, handler.GetType().ToString()), error);
            }
        }