gpt4 book ai didi

asp.net-mvc - 创建带有文件扩展名的ActionResult的推荐方法

转载 作者:行者123 更新时间:2023-12-03 12:24:34 25 4
gpt4 key购买 nike

我需要在具有.csv文件类型的ASP.NET MVC应用程序中创建ActionResult。

我将向我的营销合作伙伴提供一个“请勿 call ”电子邮件列表,并且我希望它在文件类型中具有.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” header 。创建这样的自定义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"
*/
};

关于asp.net-mvc - 创建带有文件扩展名的ActionResult的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/989927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com