IEnumerable to Stream for FileStreamResult

前端 未结 2 1613
梦毁少年i
梦毁少年i 2021-01-14 08:38

I have an IEnumerable, which is \"streamed\" per yield statements from a method. Now I want to convert this enumerable to a Str

2条回答
  •  情深已故
    2021-01-14 09:13

    You have to create your ActionResult class to achieve lazy evaluation. You have create mix of ContentResult an FileStreamResult classes to achieve behaviour like FileStreamResult with ability to set result encoding. Good starting point is FileResult abstract class:

    public class EnumerableStreamResult : FileResult
    {
    
        public IEnumerable Enumerable
        {
            get;
            private set;
        }
    
        public Encoding ContentEncoding
        {
            get;
            set;
        }
    
        public EnumerableStreamResult(IEnumerable enumerable, string contentType)
            : base(contentType)
        {
            if (enumerable == null)
            {
                throw new ArgumentNullException("enumerable");
            }
            this.Enumerable = enumerable;
        }
    
        protected override void WriteFile(HttpResponseBase response)
        {
            Stream outputStream = response.OutputStream;
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Enumerable != null)
            {
                foreach (var item in Enumerable)
                {
    
                    //do your stuff here
                    response.Write(item);
                }
            }
        }
    }
    

提交回复
热议问题