public void ExecuteResult()
        {
            // Arrange
            string content = "Some content.";
            string contentType = "Some content type.";
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();
            mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable();

            ContentResult result = new ContentResult
            {
                Content = content,
                ContentType = contentType,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
Example #2
0
        public void ExecuteResult()
        {
            // Arrange
            string   content         = "Some content.";
            string   contentType     = "Some content type.";
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>(MockBehavior.Strict);

            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType     = contentType).Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();
            mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable();

            ContentResult result = new ContentResult
            {
                Content         = content,
                ContentType     = contentType,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
Example #3
0
        public override void ExecuteResult(ControllerContext context)
        {
            var sb = new StringBuilder();

            foreach (var action in actions)
            {
                action.ExecuteResult(context, sb);
            }

            var isAjaxRequest = context.HttpContext.Request.IsAjaxRequest();

            if (isAjaxRequest)
            {
                var result = new ContentResult {
                    Content = sb.ToString(), ContentType = "application/x-javascript"
                };
                result.ExecuteResult(context);
            }
            else
            {
                sb.Insert(0, "<html><head><script type=\"text/javascript\">");
                sb.Append("</script></head></html>");

                var result = new ContentResult {
                    Content = sb.ToString(), ContentType = "text/html"
                };
                result.ExecuteResult(context);
            }
        }
        public void NullContentIsNotOutput()
        {
            // Arrange
            string   contentType     = "Some content type.";
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext
            .SetupSet(c => c.HttpContext.Response.ContentType = contentType)
            .Verifiable();
            mockControllerContext
            .SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding)
            .Verifiable();

            ContentResult result = new ContentResult
            {
                ContentType     = contentType,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
Example #5
0
        public override void ExecuteResult(ControllerContext context)
        {
            var contentResult = new ContentResult();

            contentResult.Content     = ModelToSerialize.Serialize();
            contentResult.ContentType = "text/xml";
            contentResult.ExecuteResult(context);
        }
Example #6
0
        private void OutputString(string content, string contentType, ControllerContext context)
        {
            var cr = new ContentResult
            {
                Content     = content,
                ContentType = contentType
            };

            cr.ExecuteResult(context);
        }
Example #7
0
        public override void ExecuteResult(ControllerContext context)
        {
            var contentResult = new ContentResult
            {
                Content     = _data.ToJson(),
                ContentType = "application/json"
            };

            contentResult.ExecuteResult(context);
        }
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            ContentResult result = new ContentResult()
            {
                Content         = Content,
                ContentEncoding = ContentEncoding,
                ContentType     = ContentType
            };

            result.ExecuteResult(context);
        }
        /// <summary>
        /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult" /> class.
        /// </summary>
        /// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
        /// <exception cref="NotImplementedException"></exception>
        public override void ExecuteResult(ControllerContext context)
        {
            this.Result.ExecuteResult(context);

            var script = Sitecore.Context.Items[Constants.MvcWebFormRulesScriptKey] as string;

            if (!string.IsNullOrEmpty(script))
            {
                var content = new ContentResult {
                    Content = InlineJs.SafeScriptWrapping.FormatWith(script)
                };
                content.ExecuteResult(context);
            }
        }
Example #10
0
 /// <summary>
 /// 执行结果
 /// </summary>
 /// <param name="context">内容上下文</param>
 public override void ExecuteResult(ControllerContext context)
 {
     var contentType = "application/json";
     var json = Infrastructure.Utility.JsonSerializer.Serialize(this.model);
     var callback = context.RequestContext.HttpContext.Request["callback"];
     if (callback == null)
     {
         var result = new ContentResult() { ContentType = contentType, Content = json };
         result.ExecuteResult(context);
     }
     else
     {
         var result = new ContentResult { Content = string.Format("{0}({1})", callback, json) };
         result.ExecuteResult(context);
     }
 }
        public override void ExecuteResult(ControllerContext context)
        {
            EncryptedPayloadWrapper <T> wrap = new EncryptedPayloadWrapper <T>(_result);
            var objectResult = new ContentResult();

            objectResult.Content = wrap.ToString();
            //objectResult.StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status200OK;
            objectResult.ContentType = "text/text";

            //{
            //    StatusCode =  // _result.Exception != null
            //    //? Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError

            //};

            objectResult.ExecuteResult(context);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            var request  = context.HttpContext.Request;

            ViewData["RequestedUrl"] = GetRequestedUrl(request);
            ViewData["ReferrerUrl"]  = GetReferrerUrl(request, request.Url.OriginalString);

            response.StatusCode = 404;
            // Prevent IIS7 from overwriting our error page!
            response.TrySkipIisCustomErrors = true;
            var    req  = context.HttpContext.Request;
            string mesg = "{1}IP地址:{0}{1}浏览器:{2}({3}){1}网址:{4}{1}".AkFormat(req.UserHostAddress, Environment.NewLine, req.Browser.Type, req.Browser.Browser, req.Url);

            if (AtawAppContext.Current.Logger != null)
            {
                AtawAppContext.Current.Logger.Info(mesg);
            }


            if (GlobalVariable.IsAjax)
            {
                JsResponseResult <string> jsRes = new JsResponseResult <string>()
                {
                    ActionType = JsActionType.Alert
                };
                jsRes.Content = req.Url.ToString() + " 未找到";
                ContentResult res = new ContentResult();
                res.Content = AtawAppContext.Current.FastJson.ToJSON(jsRes);
                response.Clear();
                res.ExecuteResult(context);
            }
            else
            {
                ViewResult viewResult = null;
                viewResult = new ViewResult
                {
                    ViewName = ViewName,
                    ViewData = ViewData
                };
                response.Clear();
                viewResult.ExecuteResult(context);
            }
        }
Example #13
0
        public override void ExecuteResult(ControllerContext context)
        {
            var itemSeparator = ";";

            var sb = new StringBuilder();

            if (Data == null)
            {
                return;                 // do nothing
            }

            var firstRow = Data.Rows.FirstOrDefault();

            if (firstRow == null)
            {
                return;                 // do nothing
            }

            foreach (var field in firstRow.Fields)
            {
                sb.Append(field.DisplayName + itemSeparator);
            }

            sb.AppendLine();

            foreach (var record in Data.Rows)
            {
                foreach (var field in record.Fields)
                {
                    sb.Append((field.Data != null) ? field.Data.ToString() : String.Empty);
                    sb.Append(itemSeparator);
                }
                sb.AppendLine();
            }

            var result = new ContentResult {
                ContentType     = "text/csv",
                Content         = sb.ToString(),
                ContentEncoding = Encoding.Default
            };

            result.ExecuteResult(context);
        }
Example #14
0
        private void OutputExport(ControllerContext context)
        {
            var fileId     = context.HttpContext.Request.QueryString["__rdlReport"];
            var type       = context.HttpContext.Request.QueryString["__rdlType"];
            var fileName   = context.HttpContext.Request.QueryString["__rdlName"];
            var targetFile = Path.Combine(Path.GetTempPath(), fileId + "." + type);

            if (File.Exists(targetFile))
            {
                var fpr = new FilePathResult(targetFile, "application/octet-stream");
                var fn  = string.IsNullOrWhiteSpace(fileName) ? $"报表导出({DateTime.Now:yyyyMMddHHmmss})" : fileName;
                fpr.FileDownloadName = fn + "." + type;
                fpr.ExecuteResult(context);
            }
            else
            {
                var cr = new ContentResult {
                    Content = "<script>alert('对不起,请需要下载的文件不存在,请重试!');window.close();</script>"
                };
                cr.ExecuteResult(context);
            }
        }
        public void NullContentIsNotOutput()
        {
            // Arrange
            string contentType = "Some content type.";
            Encoding contentEncoding = Encoding.UTF8;

            // Arrange expectations
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();
            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();

            ContentResult result = new ContentResult
            {
                ContentType = contentType,
                ContentEncoding = contentEncoding
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
Example #16
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);
    }