Recommended way to create an ActionResult with a file extension

前端 未结 4 1474
余生分开走
余生分开走 2020-12-24 02:58

I need to create an ActionResult in an ASP.NET MVC application which has a .csv filetype.

I will provide a \'do not call\' email list to my marketing partners and i

4条回答
  •  滥情空心
    2020-12-24 03:32

    I think your Response MUST contain "Content-Disposition" header in this case. Create custom ActionResult like this:

    public class MyCsvResult : ActionResult {
    
        public string Content {
            get;
            set;
        }
    
        public Encoding ContentEncoding {
            get;
            set;
        }
    
        public string Name {
            get;
            set;
        }
    
        public override void ExecuteResult(ControllerContext context) {
            if (context == null) {
                throw new ArgumentNullException("context");
            }
    
            HttpResponseBase response = context.HttpContext.Response;
    
            response.ContentType = "text/csv";
    
            if (ContentEncoding != null) {
                response.ContentEncoding = ContentEncoding;
            }
    
            var fileName = "file.csv";
    
            if(!String.IsNullOrEmpty(Name)) {
                fileName = Name.Contains('.') ? Name : Name + ".csv";
            }
    
            response.AddHeader("Content-Disposition",
                String.Format("attachment; filename={0}", fileName));
    
            if (Content != null) {
                response.Write(Content);
            }
        }
    }
    

    And use it in your Action instead of ContentResult:

    return new MyCsvResult {
        Content = Emails.Aggregate((a,b) => a + Environment.NewLine + b)
        /* Optional
         * , ContentEncoding = ""
         * , Name = "DoNotEmailList.csv"
         */
    };
    

提交回复
热议问题