asp.net-mvc – 使用文件扩展名创建ActionResult的推荐方法

我需要在具有.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"
     */
};

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....