我需要在具有.csv文件类型的ASP.NET MVC应用程序中创建一个ActionResult。
我将向我的营销合作伙伴提供一个“不要打电话”的电子邮件列表,我希望它能够在filetype中添加一个.csv扩展名。然后它会自动在Excel中打开。
http://www.example.com/mailinglist/donotemaillist.csv?password=12334
我已经成功地完成了如下,但我想确保这是绝对最好和推荐的方式做到这一点。
[ActionName("DoNotEmailList.csv")] public ContentResult DoNotEmailList(string username,string password) { return new ContentResult() { Content = Emails.Aggregate((a,b)=>a+Environment.NewLine + b),ContentType = "text/csv" }; }
这个Actionmethod会回应上面的链接。
我只是想知道是否有任何可能的任何意外的冲突,有这样的文件扩展名与任何不同版本的IIS,任何种类的ISAPI过滤器,或任何我现在不能想到的东西。
我需要100%肯定,因为我会把这个提供给外部合作伙伴,不想再想改变主意了。我真的看不到任何问题,但也可能是某些晦涩的东西 – 或者另外一个“MVC”就像这样做。
解决方法
在这种情况下,我认为你的回应必须包含“Content-disposition”头。创建自定义ActionResult,如下所示:
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); } } }
并在您的Action中使用它而不是ContentResult:
return new MyCsvResult { Content = Emails.Aggregate((a,b) => a + Environment.NewLine + b) /* Optional *,ContentEncoding = "" *,Name = "DoNotEmailList.csv" */ };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。