如何使用FilePathResult.WriteFile?

时间:2011-03-07 11:52:34

标签: asp.net asp.net-mvc asp.net-mvc-3

背景

我有一个包含秘密报告文件的安全文件夹(pdf格式)。每个文件对应一个用户。

我的网站是使用Asp.net MVC 3 Razor开发的。

当用户导航到http://mydomain.com/UserProfile/Report时,它会调用GET处理操作方法Report并返回带有提交按钮Download Report的视图。

当用户单击该按钮时,它将调用POST处理操作方法。验证将在此操作方法中完成。验证成功通过后,操作方法将返回所请求的文件。

问题

您能举例说明如何实现POST处理操作方法吗?

这是骨架:

[HttpPost]
public ActionResult Report(/*any parameter I don't know*/)
{
    if(!IsAuthenticated())
        return RedirectToActionLink("SomeActionMethod","SomeController");
    else
    {
       // what should I do here?
       // Asssume my secret folder is d:\mydomain.com\secret and the public folder is d:\mydomain.com\httpdoc
    }
}

2 个答案:

答案 0 :(得分:3)

以下是将文件返回给客户端的方法:

public FileContentResult Report(/*any parameter I don't know*/)
{
    if(!IsAuthenticated())
        return RedirectToActionLink("SomeActionMethod","SomeController");
    else
    {
        // Read the file from your location into a byte array named content
        Response.ContentType = "application/pdf";
        return new FileContentResult(content, "application/pdf");

    }
}

答案 1 :(得分:2)

您可以使用File方法返回FileContentResult

[HttpPost]
public FileContentResult Report()
{
  if(!IsAuthenticated())
    return RedirectToActionLink("SomeActionMethod","SomeController");
  else
  {
    string path = @"d:\mydomain.com\secret\" + fileName;
    return File(path, "application/pdf"); ////
  }
}
相关问题