Beispiel #1
0
        private static void OutputClientValidation(HttpResponseBase response, FormContext formContext) {
            if (!formContext.ClientValidationEnabled) {
                return; // do nothing
            }

            // output a call that resembles:
            // _clientValidationFunction(validationObject, userContext);

            string validationJson = formContext.GetJsonValidationMetadata();

            string userContextJson = (formContext.ClientValidationState != null)
                ? new JavaScriptSerializer().Serialize(formContext.ClientValidationState)
                : "null";

            string scriptWithCorrectNewLines = _clientValidationScript.Replace("\r\n", Environment.NewLine);
            string formatted = String.Format(CultureInfo.InvariantCulture, scriptWithCorrectNewLines,
                formContext.ClientValidationFunction, validationJson, userContextJson);

            response.Write(formatted);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (this.Data != null)
            {
                //JsonConvert.SerializeObject(
                //JavaScriptSerializer serializer = GetJavaScriptSerializer();
                //response.Write(serializer.Serialize(Data));
                ////serializer.RegisterConverters(
                //string jsonString = jss.Serialize(Data);
                //string p = @"\\/Date\((\d+)\)\\/";
                //MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
                //Regex reg = new Regex(p);
                //jsonString = reg.Replace(jsonString, matchEvaluator);
                var result = JsonConvert.SerializeObject(Data, JavaScriptConverters);
                response.Write(result);
            }
        }
Beispiel #3
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("JSON GET is not allowed");
            }

            try
            {
                HttpResponseBase response = context.HttpContext.Response;
                response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

                if (this.ContentEncoding != null)
                {
                    response.ContentEncoding = this.ContentEncoding;
                }
                if (this.Data == null)
                {
                    return;
                }

                var scriptSerializer = JsonSerializer.Create(this.Settings);

                using (var sw = new StringWriter())
                {
                    scriptSerializer.Serialize(sw, this.Data);
                    response.Write(sw.ToString());
                }
            }
            catch
            {
                base.ExecuteResult(context);
            }
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                // ScriptingJsonSerializationSection section = ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as ScriptingJsonSerializationSection;

                serializer.MaxJsonLength = Int32.MaxValue;
                //serializer.RecursionLimit = section.RecursionLimit;
                // }
                response.Write(serializer.Serialize(Data));
            }
        }
Beispiel #5
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpRequestBase request = context.HttpContext.Request;

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("JSON GET is not allowed");
            }

            string contentType = this.ContentType;

            if (string.IsNullOrEmpty(contentType))
            {
                bool isAjaxRequest = string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest");
                contentType = isAjaxRequest ? "application/json" : "text/html";
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType     = contentType;
            response.ContentEncoding = this.ContentEncoding ?? Encoding.UTF8;

            if (this.Data != null)
            {
                JsonSerializer serializer = JsonSerializer.Create(this.Settings);
                using (StringWriter sw = new StringWriter())
                {
                    serializer.Serialize(sw, this.Data);
                    response.Write(sw.ToString());
                }
            }
        }
Beispiel #6
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (_table.SaveAs)
            {
                response.ContentType = CSV_CONTENT_TYPE;
                response.AddHeader(
                    "Content-Disposition",
                    string.Format(
                        "attachment; filename={0}",
                        string.Format("{0:yyyyMMdd-HHmm}.csv", DateTime.Now)
                        )
                    );
                // TODO: handle bool && enum
                byte[] bytes = new Csv().Export(_table.Data);
                response.OutputStream.Write(bytes, 0, bytes.Length);
            }
            else
            {
                response.ContentType = JSON_CONTENT_TYPE;
                response.Write(new JsonNetSerializer().Get(
                                   new
                {
                    draw            = _table.Draw,
                    recordsTotal    = _table.RecordsTotal,
                    recordsFiltered = _table.RecordsFiltered,
                    data            = _table.Data
                },
                                   true
                                   ));
            }
        }
Beispiel #7
0
        /// <summary>
        /// 重写执行视图
        /// </summary>
        /// <param name="context">上下文</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (this.Data != null)
            {
                var jSetting = new JsonSerializerSettings {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Include
                };
                var nullFormat = new CustomJsonConverter {
                    PropertyNullValueReplaceValue = "", DateTimeFormat = FormateStr
                };
                jSetting.Converters.Add(nullFormat);

                jSetting.MaxDepth = Int32.MaxValue;
                string jsonString = JsonConvert.SerializeObject(Data, Formatting.Indented, jSetting);
                response.Write(jsonString);
            }
        }
Beispiel #8
0
        public static void Apply(this CommandResult commandResult, HttpResponseBase response)
        {
            if (commandResult == null)
            {
                throw new ArgumentNullException(nameof(commandResult));
            }

            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            response.Cache.SetCacheability((HttpCacheability)commandResult.Cacheability);

            ApplyCookies(commandResult, response);

            if (commandResult.HttpStatusCode == HttpStatusCode.SeeOther || commandResult.Location != null)
            {
                if (commandResult.Location == null)
                {
                    throw new InvalidOperationException("Missing Location on redirect.");
                }
                if (commandResult.HttpStatusCode != HttpStatusCode.SeeOther)
                {
                    throw new InvalidOperationException("Invalid HttpStatusCode for redirect, but Location is specified");
                }

                response.Redirect(commandResult.Location.OriginalString);
            }
            else
            {
                response.StatusCode  = (int)commandResult.HttpStatusCode;
                response.ContentType = commandResult.ContentType;
                response.Write(commandResult.Content);

                response.End();
            }
        }
Beispiel #9
0
        /// <summary>
        /// 执行结果
        /// </summary>
        /// <param name="context">上下文</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("此请求已被阻止,因为当用在 GET 请求中时,会将敏感信息透漏给第三方网站。若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet。");
            }
            HttpResponseBase base2 = context.HttpContext.Response;

            base2.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
            if (this.ContentEncoding != null)
            {
                base2.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data == null)
            {
                return;
            }
            JsonSerializerSettings setting = new JsonSerializerSettings();

            //不理Null值
            setting.NullValueHandling = NullValueHandling.Ignore;
            //格式化命名方式
            setting.ContractResolver = NamingType == NamingType.CamelCase ? new CamelCasePropertyNamesContractResolver() : new DefaultContractResolver();
            //是否缩进
            setting.Formatting = Formatting;
            //格式化时间
            if (!string.IsNullOrEmpty(DateTimeFormat))
            {
                setting.DateFormatString = DateTimeFormat;
            }
            string jsonResult = JsonConvert.SerializeObject(this.Data, setting);

            base2.Write(jsonResult);
        }
Beispiel #10
0
        public override void ExecuteResult(ControllerContext context)
        {
            StringBuilder output = new StringBuilder();

            if (string.IsNullOrEmpty(ClassName))
            {
                Tag message = new Tag("div", new { Class = "error" }).Text("ClassName not specified");
                output = new StringBuilder(message.ToHtmlString());
            }
            else
            {
                Incubator incubator = ServiceProxySystem.Incubator;
                Type      type;
                incubator.Get(ClassName, out type);
                if (type == null)
                {
                    Tag message = new Tag("div", new { Class = "error" }).Text("The specified className ({0}) was not registered in the ServiceProxySystem"._Format(ClassName));
                    output = new StringBuilder(message.ToHtmlString());
                }
                else
                {
                    InputFormBuilder formBuilder = new InputFormBuilder(type);
                    formBuilder.Layout = Layout;
                    Dictionary <string, object> defaults = new Dictionary <string, object>();
                    if (Defaults != null)
                    {
                        defaults = Defaults.PropertiesToDictionary();
                    }

                    TagBuilder tag = formBuilder.MethodForm(MethodName, defaults);
                    output = new StringBuilder(tag.ToMvcHtml().ToString());
                }
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.Write(output.ToString());
        }
        /// <summary>
        /// When called by the action invoker, writes the JSON formatted result to the response.
        /// </summary>
        /// <param name="context">The context that the result is executed in.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                serializer.RegisterConverters(new JavaScriptConverter[] { new JqGridScriptConverter() });
                string data = serializer.Serialize(Data);


                response.Write(data);
            }
        }
Beispiel #12
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data != null)
            {
                response.Write(NewtonsoftSerialize(this.Data));
                response.End();
            }
        }
Beispiel #13
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            //if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            //    throw new InvalidOperationException("JSON GET is not allowed");
            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data == null)
            {
                return;
            }
            var result = JsonConvert.SerializeObject(this.Data, this.Settings);

            response.Write(result);
        }
Beispiel #14
0
    public void ToExcel(HttpResponseBase Response, object clientsList, string fileName)
    {
        try
        {
            var grid = new System.Web.UI.WebControls.GridView();
            grid.DataSource = clientsList;
            grid.DataBind();
            Response.ClearContent();
            //var filename = "MatHang_" + DateTime.Now.ToString("yyyyMMdd")+".xls";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
            Helpers.Config.SaveToLog(ex.ToString());
        }
    }
Beispiel #15
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data == null)
            {
                return;
            }

            var scriptSerializer = JsonSerializer.Create(this.Settings);

            using (var sw = new StringWriter())
            {
                scriptSerializer.Serialize(sw, this.Data);
                response.Write(sw.ToString());
            }
        }
Beispiel #16
0
        /// <summary>
        /// Executes the result.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = ContentType.SafeToString(HttpConstants.ContentType.Json);

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data == null)
            {
                return;
            }

            var scriptSerializer = JsonSerializer.Create(JsonExtension.SafeJsonSerializationSettings);

            using (var sw = new StringWriter())
            {
                scriptSerializer.Serialize(sw, Data);
                response.Write(sw.ToString());
            }
        }
Beispiel #17
0
            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException("context");
                }

                HttpResponseBase response = context.HttpContext.Response;

                response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
                if (ContentEncoding != null)
                {
                    response.ContentEncoding = ContentEncoding;
                }

                if (Data != null)
                {
                    JavaScriptSerializer serializer = CreateJsonSerializer();
                    string serialized = serializer.Serialize(Data);
                    logger.Debug("serialized data: " + serialized);
                    response.Write(serialized);
                }
            }
        /// <summary>
        ///     Serialises the response and writes it out to the response object
        /// </summary>
        /// <param name="context">The execution context</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            // set content type
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

            // set content encoding
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (ResponseBody != null)
            {
                response.Write(JsonConvert.SerializeObject(ResponseBody, Formatting, Settings));
            }
        }
        private void SerializeData(HttpResponseBase response)
        {
            if (ErrorMessages.Any())
            {
                Data = new
                {
                    ErrorMessage  = string.Join("\n", ErrorMessages),
                    ErrorMessages = ErrorMessages.ToArray()
                };

                // Bad Request
                // The request could not be understood by the server due to malformed syntax.
                // The client SHOULD NOT repeat the request without modifications.
                response.StatusCode = 400;
            }

            if (Data == null)
            {
                return;
            }

            response.Write(Data.ToJson(IncludeNull, MaxDepth));
        }
Beispiel #20
0
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            Type type = Data.GetType();
            response.Write(String.Format("{{success: true, msg: \"{0}\", data:", msg));
            if (type == typeof(DataRow))
            {
                response.Write(JSonHelper.Serialize(Data, true));
            }
            else if (type == typeof(DataTable))
            {
                response.Write(JSonHelper.Serialize(Data, true));
            }
            else if (type == typeof(DataSet))
            {
                response.Write(JSonHelper.Serialize(Data, true));
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                response.Write(serializer.Serialize(Data));
            }
            response.Write("}");
        }
    }
Beispiel #21
0
        private void writeToResponse(HttpContextBase httpContext)
        {
            var feed = new SyndicationFeed
            {
                Title    = new TextSyndicationContent(_feedTitle.CorrectRtl()),
                Language = _language,
                Items    = _allItems
            };

            addChannelLinks(httpContext, feed);

            string feedData = syndicationFeedToString(feed);

            // Interoperability with feed readers could be improved by avoiding Namespace Prefix: a10
            feedData = feedData.Replace("xmlns:a10", "xmlns:atom").Replace("a10:", "atom:");

            HttpResponseBase response = httpContext.Response;

            response.ContentEncoding = Encoding.UTF8;
            response.ContentType     = "application/rss+xml";
            response.Write(feedData);
            response.End();
        }
Beispiel #22
0
        /// <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 within which the result is executed.</param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
        public override void ExecuteResult(ControllerContext context)
        {
            Invariant.IsNotNull(context, "context");

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(ExceptionMessages.JsonGet);
            }

            HttpResponseBase httpResponse = context.HttpContext.Response;

            httpResponse.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

            if (ContentEncoding != null)
            {
                httpResponse.ContentEncoding = ContentEncoding;
            }

            if (Data != null)
            {
                httpResponse.Write(Data.ToJson(JsonConverters));
            }
        }
Beispiel #23
0
            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException("context");
                }
                if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidOperationException("GetNotAllowed");
                }
                HttpResponseBase response = context.HttpContext.Response;

                response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;

                if (ContentEncoding != null)
                {
                    response.ContentEncoding = ContentEncoding;
                }
                if (Data != null)
                {
                    response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data));
                }
            }
Beispiel #24
0
        /// <summary>
        /// Enables processing of the result of an action method by a
        /// custom type that inherits from
        /// <see cref="T:System.Web.Mvc.ActionResult"/>.
        /// </summary>
        /// <param name="context">The context within which the
        /// result is executed.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/javascript";
            }

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            if (Callback == null || Callback.Length == 0)
            {
                Callback = context.HttpContext.Request.QueryString["jsoncallback"];
            }

            if (Data != null)
            {
                // The JavaScriptSerializer type was marked as obsolete
                // prior to .NET Framework 3.5 SP1
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string ser = serializer.Serialize(Data);
                response.Write(Callback + "(" + ser + ");");
            }
        }
Beispiel #25
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("MvcResources.JsonRequest_GetNotAllowed");
            }
            HttpResponseBase base2 = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
            {
                base2.ContentType = this.ContentType;
            }
            else
            {
                base2.ContentType = "application/json";
            }
            if (this.ContentEncoding != null)
            {
                base2.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data != null)
            {
                //转换System.DateTime的日期格式到 ISO 8601日期格式
                //ISO 8601 (如2008-04-12T12:53Z)
                IsoDateTimeConverter isoDateTimeConverter = new IsoDateTimeConverter();
                //设置日期格式
                isoDateTimeConverter.DateTimeFormat = DateTimeFormat;
                //序列化
                String jsonResult = JsonConvert.SerializeObject(this.Data, isoDateTimeConverter);
                //相应结果
                base2.Write(jsonResult);
            }
        }
Beispiel #26
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            if (File.Exists(FileName))
            {
                FileStream fs         = null;
                byte[]     fileBuffer = new byte[BufferSize];//每次读取4096字节大小的数据
                try
                {
                    using (fs = File.OpenRead(FileName))
                    {
                        long totalLength = fs.Length;
                        response.ContentType = ContentType;
                        response.AddHeader("Content-Length", totalLength.ToString());
                        response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Path.GetFileName(FileName)));
                        while (totalLength > 0 && response.IsClientConnected)       //持续传输文件
                        {
                            int length = fs.Read(fileBuffer, 0, fileBuffer.Length); //每次读取4096个字节长度的内容
                            fs.Flush();
                            response.OutputStream.Write(fileBuffer, 0, length);     //写入到响应的输出流
                            response.Flush();                                       //刷新响应
                            totalLength = totalLength - length;
                        }
                        response.Close();//文件传输完毕,关闭相应流
                    }
                }
                catch (Exception ex)
                {
                    response.Write(ex.Message);
                }
                finally
                {
                    fs?.Close();//最后记得关闭文件流
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Executes the result.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("This request has been blocked because sensitive information could "
                                                    + "be disclosed to third party web sites when this is used in a GET request. "
                                                    + "To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = !string.IsNullOrEmpty(this.ContentType)
                ? this.ContentType
                : "application/json";

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (this.Data != null)
            {
                JsonSerializer scriptSerializer = JsonSerializer.Create(this.Settings);

                using (StringWriter sw = new StringWriter())
                {
                    scriptSerializer.Serialize(sw, this.Data);
                    response.Write(sw.ToString());
                }
            }
        }
Beispiel #28
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("JSON GET is not allowed");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data == null)
            {
                return;
            }

            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();

            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
            //var scriptSerializer = JsonSerializer.Create(this.Settings);
            //using (var sw = new StringWriter())
            //{
            //    scriptSerializer.Serialize(sw, this.Data);
            //    response.Write(sw.ToString());
            //}
        }
Beispiel #29
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("JsonRequest Get Not Allowed");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                var jSetting = new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };
                var json = JsonConvert.SerializeObject(Data, Formatting.None, jSetting);

                response.Write(json);
            }
        }
        protected virtual void SerializeData(HttpResponseBase response)
        {
            var originalData = Data;

            if (ErrorMessages.Any())
            {
                Data = new
                {
                    Success       = false,
                    Content       = originalData,
                    ErrorMessages = ErrorMessages.ToArray(),
                    RequestTime   = DateTime.Now,
                };

                response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
            else
            {
                Data = new
                {
                    Success       = true,
                    Content       = originalData,
                    ErrorMessages = String.Empty,
                    RequestTime   = DateTime.Now,
                };

                response.StatusCode = (int)HttpStatusCode.OK;
            }

            var settings = new JsonSerializerSettings
            {
                ContractResolver     = new MundiPagg.Infra.Utils.CamelCasePropertyNamesContractResolver(),
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            };

            response.Write(JsonConvert.SerializeObject(Data, settings));
        }
            /// <summary>
            /// 说明:重写ExecueResult方法
            /// 作者:CallmeYhz
            /// </summary>
            /// <param name="context"></param>
            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException("context");
                }
                if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                    String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidOperationException(error);
                }
                HttpResponseBase response = context.HttpContext.Response;

                if (!String.IsNullOrEmpty(ContentType))
                {
                    response.ContentType = ContentType;
                }
                else
                {
                    response.ContentType = "application/json";
                }
                if (ContentEncoding != null)
                {
                    response.ContentEncoding = ContentEncoding;
                }
                if (Data != null)
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    string jsonstring = serializer.Serialize(Data);
                    //string hashOldPassword = @"\\/Date\((\param+)\+\param+\)\\/";
                    string         p = @"\\/Date\(-{0,1}\d+\)\\/";
                    MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
                    Regex          reg            = new Regex(p);
                    jsonstring = reg.Replace(jsonstring, matchEvaluator);
                    response.Write(jsonstring);
                }
            }