Esempio n. 1
0
            // IHttpAsyncHandler members
            public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback asyncCallback, object extraData)
            {
                IAsyncResult result = null;
                // Get the controller type
                string controllerName = _requestContext.RouteData.GetRequiredString("controller");

                // Obtain an instance of the controller
                _factory = ControllerBuilder.Current.GetControllerFactory();
                var controller = _factory.CreateController(_requestContext, controllerName) as ControllerBase;
                if (controller == null)
                  throw new InvalidOperationException("Can't locate the controller " + controllerName);

                try
                {
                  _asyncController = controller as AsyncController;
                  if (_asyncController == null)
                throw new InvalidOperationException("Controller isn't an AsyncController.");

                  // Set up asynchronous processing
                  _httpContext = HttpContext.Current; // Save this for later

                  result = _asyncController.Execute(_requestContext, asyncCallback);
                }
                finally
                {
                  if (result == null || result.CompletedSynchronously)
                  {
                this._factory.ReleaseController(controller);
                  }
                }

                return result;
            }
        internal IController CreateController(IControllerFactory controllerFactory, RequestContext requestContext, string controllerName)
        {
            try
            {
                return controllerFactory.CreateController(requestContext, controllerName);
            }
            catch (HttpException ex)
            {
                if (ex.GetHttpCode() == 404)
                {
                    return null;
                }

                throw;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 通过Http上下文对象创建对应的controller工厂和controller
        /// </summary>
        /// <param name="httpContext">封装的Http上下文</param>
        /// <param name="controller">返回当前请求的controller实例</param>
        /// <param name="factory">返回controller工厂实例</param>
        private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)
        {
            // If request validation has already been enabled, make it lazy. This allows attributes like [HttpPost] (which looks
            // at Request.Form) to work correctly without triggering full validation.
            // Tolerate null HttpContext for testing.
            HttpContext currentContext = HttpContext.Current;
            if (currentContext != null)
            {
                bool? isRequestValidationEnabled = ValidationUtility.IsValidationEnabled(currentContext);
                if (isRequestValidationEnabled == true)
                {
                    ValidationUtility.EnableDynamicValidation(currentContext);
                }
            }

            // 在响应头中返回MVC的版本号信息 如:X-AspNetMvc-Version  5.0
            AddVersionHeader(httpContext);
            // 移除路由数据中的可选项Optional
            RemoveOptionalRoutingParameters();

            // 获取当前请求的控制器名称
            // Get the controller type
            string controllerName = RequestContext.RouteData.GetRequiredString("controller");

            // 通过工厂创建controller的实例
            // Instantiate the controller and call Execute
            factory = ControllerBuilder.GetControllerFactory();
            controller = factory.CreateController(RequestContext, controllerName);
            if (controller == null)
            {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        MvcResources.ControllerBuilder_FactoryReturnedNull,
                        factory.GetType(),
                        controllerName));
            }
        }
Esempio n. 4
0
        private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)
        {
            AddVersionHeader(httpContext);
            RemoveOptionalRoutingParameters();

            // Get the controller type
            string controllerName = RequestContext.RouteData.GetRequiredString("controller");

            // Instantiate the controller and call Execute
            factory = ControllerBuilder.GetControllerFactory();
            controller = factory.CreateController(RequestContext, controllerName);
            if (controller == null) {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        MvcResources.ControllerBuilder_FactoryReturnedNull,
                        factory.GetType(),
                        controllerName));
            }
        }
        /// <summary>
        /// Creates a controller using the controller factory
        /// </summary>
        private static ControllerBase CreateController(ControllerContext context, IControllerFactory factory, RouteDefinition routeDef)
        {
            var controller = factory.CreateController(context.RequestContext, routeDef.ControllerName) as ControllerBase;

            if (controller == null)
                throw new InvalidOperationException("Could not create controller with name " + routeDef.ControllerName + ".");

            return controller;
        }
        /// <summary>
        /// Dispatches the request.
        /// </summary>
        /// <param name="controllerFactory">The controller factory.</param>
        /// <param name="controller">The controller.</param>
        /// <param name="action">The action.</param>
        private void DispatchRequest(IControllerFactory controllerFactory, string controller, string action)
        {
            var route = GetRoute(controller, action);
            _requestContext.RouteData.Values["x-action"] = action;
            _requestContext.RouteData.Values["x-controller"] = controller;

            if (route != null)
            {
                _requestContext.RouteData.Values["controller"] = route.Controller;
                _requestContext.RouteData.Values["action"] = route.Action;

                if (route.Area != string.Empty)
                {
                    _requestContext.RouteData.DataTokens["area"] = route.Area;
                }

                controller = route.Controller;
            }
            else
            {
                _requestContext.RouteData.Values["action"] = _configuration.DefaultAction;
                controller = _configuration.DefaultController;
            }

            var viewController = controllerFactory.CreateController(_requestContext, controller);
            if (viewController != null)
            {
                viewController.Execute(_requestContext);
            }
        }
Esempio n. 7
0
        void Application_Error(object sender, EventArgs e)
        {
            try
            {
                //Code that runs when an unhandled error occurs
                //Exception ex = default(Exception);

                //ex = Server.GetLastError().InnerException;
                //if (ex != null)
                //{
                //    ex = Server.GetLastError().InnerException;
                //    CMODataEntryBLL.InsertErrLog(Request.Url.ToString(), ex.ToString());
                //    //HttpContext.Current.Response.Redirect("~/ErrorPageS.aspx",false);
                //    //HttpContext.Current.Response.Redirect("~/ErrorPageS.aspx", false);
                //}
                //Server.ClearError();
                HttpContext httpContext = HttpContext.Current;
                if (httpContext != null)
                {
                    RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;

                    /* 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();
                        string             controllerName    = requestContext.RouteData.GetRequiredString("controller");
                        IControllerFactory factory           = ControllerBuilder.Current.GetControllerFactory();
                        IController        controller        = factory.CreateController(requestContext, controllerName);
                        ControllerContext  controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

                        JsonResult jsonResult = new JsonResult
                        {
                            Data = new { success = false, serverError = "500" },
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet
                        };
                        jsonResult.ExecuteResult(controllerContext);
                        httpContext.Response.End();
                    }
                    else
                    {
                        //Code that runs when an unhandled error occurs
                        //Exception ex = default(Exception);

                        //ex = Server.GetLastError().InnerException;
                        //if (ex != null)
                        //{
                        string ex = httpContext.Error.Message;
                        CMODataEntryBLL.InsertErrLog(Request.Url.ToString(), ex);
                        //}
                        Response.Clear();
                        Server.ClearError();

                        var routeData = new RouteData();
                        routeData.Values["controller"] = "Login";
                        routeData.Values["action"]     = "Error";
                        Response.StatusCode            = 500;

                        IController controller = new LoginController();
                        var         rc         = new RequestContext(new HttpContextWrapper(Context), routeData);
                        controller.Execute(rc);
                    }
                }
            }
            catch { }
        }
 protected virtual bool TryCreateController(RequestContext requestContext, string controllerName, IControllerFactory controllerFactory, out ControllerBase controller)
 {
     controller = null;
     if (controllerFactory != null)
     {
         try
         {
             controller = controllerFactory.CreateController(requestContext, controllerName) as ControllerBase;
             if (controller != null)
                 return true;
         }
         catch
         {
             return false;
         }
     }
     return false;
 }
Esempio n. 9
0
        public async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequestMessage req, ILogger log)
        {
            try
            {
                var query = HttpUtility.ParseQueryString(req.RequestUri.Query);

                switch (query["path"])
                {
                case "login/logout":
                {
                    var controller = _controllerFactory.CreateController("login", req, null);
                    return(await controller.InvokeActionAsync("login/logout", req.Method));
                }

                case "login":
                {
                    var controller = _controllerFactory.CreateController("login", req, null);
                    if (req.Method == HttpMethod.Get)
                    {
                        return(await controller.InvokeActionAsync("index", req.Method));
                    }

                    return(await controller.InvokeActionAsync("login", req.Method));
                }

                case "admin":
                {
                    var controller = _controllerFactory.CreateController("admin", req, null);
                    if (req.Method == HttpMethod.Get)
                    {
                        return(await controller.InvokeActionAsync("index", req.Method));
                    }

                    return(await controller.InvokeActionAsync("login", req.Method));
                }

                default:
                {
                    var controller = _controllerFactory.CreateController("home", req, null);
                    //log.Send.Info("C# HTTP trigger function processed a request.");

                    //string requestBody = new StreamReader(req.Body).ReadToEnd();
                    //dynamic data = JsonConvert.DeserializeObject(requestBody);
                    //name = name ?? data?.name;

                    if (req.Method == HttpMethod.Get)
                    {
                        return(await controller.InvokeActionAsync("index", req.Method));
                    }

                    return(await controller.InvokeActionAsync("submit", req.Method));
                }
                }
            }
            catch (Exception ex)
            {
                //log.Error(ex.Message, ex);
                return(await _controllerFactory.CreateController("_error", req, new Dictionary <string, object>
                {
                    { "LastException", ex }
                }).InvokeActionAsync("index", req.Method));
            }
        }
 protected override object CreateInstance()
 {
     // The binding context is used in activation
     Debug.Assert(ActionBindingContext != null);
     return(_controllerFactory.CreateController(ActionContext));
 }
Esempio n. 11
0
    protected void Application_Error(object sender, EventArgs e)
    {
        string mthd = ""; string currentController = "Err";
        string currentAction = "Index";

        Exception applicationError = Server.GetLastError();

        if (applicationError is System.Security.Cryptography.CryptographicException || applicationError.InnerException is System.Security.Cryptography.CryptographicException)
        {
            MiscUtility.LogError(applicationError);
            try {
                MiscUtility.Logout();
            } catch { }
            return;
        }
        try {
            var s       = new StackTrace(applicationError);
            var thisasm = Assembly.GetExecutingAssembly();
            var methods = s.GetFrames().Select(f => f.GetMethod()).FirstOrDefault(m => m.Module.Assembly == thisasm);
            if (methods != null && !string.IsNullOrWhiteSpace(methods.Name))
            {
                mthd = string.Format("Error in Method[{0}]", methods.Name);
            }
        } catch {
            //unable to grab originating method;
        }
        if (applicationError is System.Web.HttpException && (applicationError.Message.StartsWith("The controller for path") || applicationError.Message.StartsWith("A public action method")))
        {
            MiscUtility.LogWarn("Invalid Path", applicationError);
        }
        else if (applicationError is ApplicationException && applicationError.Message.StartsWith("There are no actively monitored sites for account"))
        {
            MiscUtility.LogWarn("Inactive Account", applicationError);
        }
        else
        {
            MiscUtility.LogError(mthd, applicationError);
        }
        try {
            HttpContext httpContext = HttpContext.Current;
            if (httpContext != null)
            {
                MvcHandler mch = (MvcHandler)httpContext.CurrentHandler;
                if (mch != null && mch.RequestContext.HttpContext != null && mch.RequestContext.HttpContext.Request != null && mch.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    RequestContext requestContext = mch.RequestContext;

                    /* When the request is ajax the system can automatically handle a mistake with a JSON response.
                     * Then overwrites the default response */

                    var    contentType    = requestContext.HttpContext.Request.ContentType;
                    string controllerName = requestContext.RouteData.GetRequiredString("controller");
                    if (contentType.Contains("json"))
                    {
                        httpContext.Response.Clear();
                        if (!string.IsNullOrWhiteSpace(controllerName))
                        {
                            IControllerFactory factory           = ControllerBuilder.Current.GetControllerFactory();
                            IController        controller        = factory.CreateController(requestContext, controllerName);
                            ControllerContext  controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

                            JsonResult jsonResult = new JsonResult {
                                Data = new { success = false, message = applicationError.Message },
                                JsonRequestBehavior = JsonRequestBehavior.AllowGet
                            };
                            jsonResult.ExecuteResult(controllerContext);
                            return;
                        }
                        else
                        {
                            try {
                                httpContext.Response.ContentType = "application/json";
                                httpContext.Response.StatusCode  = 200;
                                httpContext.Response.Write(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(
                                                               new { success = false, message = applicationError.Message })
                                                           );
                            } catch { }
                        }
                        httpContext.Response.End();
                        return;
                    }
                    else if (contentType.Contains("form") || contentType.Contains("html"))
                    {
                        var htmlmsg = System.Web.HttpUtility.HtmlEncode(applicationError.Message);
                        httpContext.Response.Clear();
                        if (!string.IsNullOrWhiteSpace(controllerName))
                        {
                            IControllerFactory factory           = ControllerBuilder.Current.GetControllerFactory();
                            IController        controller        = factory.CreateController(requestContext, controllerName);
                            ControllerContext  controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);
                            ContentResult      ar = new ContentResult {
                                Content = "An unhandled error has occured: <br>" + htmlmsg
                            };
                            ar.ExecuteResult(controllerContext);
                        }
                        else
                        {
                            try {
                                httpContext.Response.ContentType = "text/html";
                                httpContext.Response.StatusCode  = 200;
                                httpContext.Response.Write("An unhandled error has occured: <br>" + htmlmsg);
                            } catch { }
                        }
                        httpContext.Response.End();
                        return;
                    }
                }
                else if (applicationError is HttpRequestValidationException)
                {
                    if (!Response.IsRequestBeingRedirected)
                    {
                        Response.Redirect("~/Err/RequestValidationError");
                    }
                }

                var MVCContext = ((MvcApplication)sender).Context;

                var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(MVCContext));


                if (currentRouteData != null)
                {
                    if (currentRouteData.Values["controller"] != null &&
                        !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                    {
                        currentController = currentRouteData.Values["controller"].ToString();
                    }

                    if (currentRouteData.Values["action"] != null &&
                        !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                    {
                        currentAction = currentRouteData.Values["action"].ToString();
                    }
                }

                var routeData  = new RouteData();
                var action     = "Index";
                var statusCode = 400;
                if (applicationError is HttpException)
                {
                    var httpEx = applicationError as HttpException;
                    statusCode = httpEx.GetHttpCode();

                    switch (httpEx.GetHttpCode())
                    {
                    case 401:
                    case 403:
                        action = "Forbidden";
                        break;

                    case 400:
                    case 404:
                        action = "MissingPage";
                        break;

                    case 500:
                    default:
                        action = "Index";
                        break;
                    }
                }
                else if (applicationError is System.Security.Authentication.AuthenticationException)
                {
                    action     = "Forbidden";
                    statusCode = 403;
                }
                else if (applicationError is System.Data.SqlClient.SqlException)
                {
                    //   applicationError = new Exception(string.Format("A SQL error has occured, please notify Customer Service."));
                }


                MVCContext.ClearError();
                MVCContext.Response.Clear();
                MVCContext.Response.StatusCode             = statusCode;
                MVCContext.Response.TrySkipIisCustomErrors = true;
                routeData.Values["controller"]             = "Err";
                routeData.Values["action"] = action;

                using (Controller controller = new Controllers.ErrController()) {
                    controller.ViewData.Model = new HandleErrorInfo(applicationError, currentController, currentAction);
                    ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(MVCContext), routeData));
                    return;
                }
            }
        } catch (Exception exception) {
            MiscUtility.LogError("Unhandled Exception handling the exception.", exception);
        }
        MiscUtility.LogError(string.Format("Unhandled Exception{0} {1}/{2}", mthd, currentAction, currentController), applicationError);
    }
Esempio n. 12
0
 /// <summary></summary>
 public IController CreateController(RequestContext requestContext, string controllerName)
 {
     return(_inner.CreateController(requestContext, controllerName));
 }
Esempio n. 13
0
 protected override object CreateInstance()
 {
     return(_controllerFactory.CreateController(Context));
 }