如何将值从操作方法传递到操作过滤器,该过滤器包含在模型中而不是控制器中



场景是这样的,我有一个 Index 操作方法正在下载一个文件,下载后我需要从我的应用程序中删除该文件。
为了删除该文件,我创建了一个动作过滤器OnActionExecuted该过滤器包含在模型中。现在的问题是我不知道如何访问此操作过滤器中的文件名?
这是操作方法:

    [HttpPost]
    [DeleteFile]
    public virtual ActionResult Index(TranscriptViewModel model)
    {
        string exportedFileName = model.GetFileName();
        if (!string.IsNullOrWhiteSpace(exportedFileName))
        {
            var fileStream = System.IO.File.OpenRead(Server.MapPath(@"App_Data" + exportedFileName));
            return File(fileStream, "application/" + model.Format.ToLower(), model.FileName);
        }
        else
        {
            model.IsShowErrorMsg = true;
            return View(model);
        }
    }

exportedFileName 是我需要在下面的操作过滤器中访问的文件名:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class DeleteFileAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        string fileName = "I need file name here";
        if (System.IO.File.Exists(fileName))
        {
            filterContext.HttpContext.Response.Flush();
            filterContext.HttpContext.Response.End();
            System.IO.File.Delete(fileName);
        }
    }
}

请建议我如何实现此要求。谢谢。

您可以尝试在控制器操作中使用以下代码,这将为您实现所需的结果:

string exportedFileName = model.GetFileName();
if (!string.IsNullOrWhiteSpace(exportedFileName))
{
context.Response.Clear();
context.Response.ContentType = "application/pdf";//change as needed
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + exportedFileName);
context.Response.TransmitFile(context.Server.MapPath(System.IO.Path.Combine(setupDirectory, setupName)));
// Add redirect here if you like
context.HttpContext.Response.Flush();
context.HttpContext.Response.End();
System.IO.File.Delete(exportedFileName);
}
else
{
model.IsShowErrorMsg = true;
return View(model);
}

最新更新