加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:42:03 所属栏目:asp.Net 来源:网络整理
导读:我需要在具有.csv文件类型的ASP.NET MVC应用程序中创建一个ActionResult。 我将向我的营销合作伙伴提供一个“不要打电话”的电子邮件列表,我希望它能够在filetype中添加一个.csv扩展名。然后它会自动在Excel中打开。 http://www.example.com/mailinglist/do
我需要在具有.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"
     */
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读