C# 应用程序文件夹外的mvc下载文件

C# 应用程序文件夹外的mvc下载文件,c#,model-view-controller,download,C#,Model View Controller,Download,我正在尝试从我的应用程序文件夹外下载一个文件 public FilePathResult DownloadFile(Guid id, string dateiname) { string pfad = @"D:\wwwroot\portal_Daten\"; return File(pfad + dateiname, "application/pdf", dateiname); } Errormessage:是一个D:\wwwroot\port

我正在尝试从我的应用程序文件夹外下载一个文件

public FilePathResult DownloadFile(Guid id, string dateiname)
    {
        string pfad = @"D:\wwwroot\portal_Daten\";

        return File(pfad + dateiname, "application/pdf", dateiname);
    }
Errormessage:是一个D:\wwwroot\portal\u Daten\8/0/6/a/e/974-aaca-426c-b7fc-e6af6c0fb52e/oeffentlich是一个物理路径,但它是预期的虚拟路径

为什么物理路径不能工作?我如何将其设置为虚拟路径

问候,,
float

您需要使用Server.MapPath并为其指定一个文件位置,以便它可以将路径映射到服务器上的相对目录

大概是

public FilePathResult DownloadFile(Guid id, string dateiname)
{
    string pfad = Server.MapPath(@"D:\wwwroot\portal_Daten\");

    var filePath = Path.Combine(pfad, dateiname);
    return File(filePath , "application/pdf", dateiname);
}

应该可以工作

我在路径中处理此问题的方法是使用自定义文件下载http处理程序(对于asp.net webforms应用程序),您可以在此处使用相同的处理程序。您甚至可以构造ActionResult的一个新子类,它可能会得到相同的结果

我这样做的方式是创建IHttpHandler的实现,处理请求并返回文件。这样,您就不局限于使用虚拟路径,只要web服务器安全配置允许,您就可以访问系统上的任何文件并将其返回到浏览器

比如:

public class MyFileHandler : IHttpHandler
{
  public bool IsReusable
  {
    get { return true; }
  }

  public void ProcessRequest(HttpContext context)
  {
    string filePath = Path.Combine(@"d:\wwwroot\portal_daten", context.Request.QueryString["dateiname"]);

    context.Response.ContentType = "application/pdf";
    context.Response.WriteFile(filePath);
  }
}
一个简单的例子,没有检查,但这是你要填写的。然后在web.config中注册处理程序:

<handlers>
  <add name="MyFileHandler" path="file.axd" type="MvcApplication4.Models.MyFileHandler" verb="GET" />
</handlers>

其中[domain]是您的域名/localhost或您正在使用的任何东西。

需要System.Web Referenced我已经更新了代码-路径实际上不正确-现在试试看-您调试过了吗-pfad的值是多少?您在示例中提供的仍然是文件夹的绝对路径。Server.MapPath()需要一个虚拟路径(如您所说),该路径通常以波浪线开头。例如“~/app\u data”。路径类似于“D:\wwwroot\portal\u Daten\”,错误消息相同。我不知道如何在Web服务器上调试网站。@elkdanger您100%正确-这不是一个虚拟路径,因此它永远不会创建正确的位置您好,我今天就试试。我不想让任何人访问我的Web服务器上的文件。另一个问题:若要使用虚拟路径,包含数据的文件夹应位于“我的应用程序”文件夹中,或者?是,如果文件位于您的网站文件结构中,您可以正常使用虚拟路径。关于我的例子,我想你误解了;我的意思是,作为程序员,您可以访问所有文件,而不仅仅是任何站点用户。通过这种方式,您可以只使用简单的URL,并解决虚拟路径的问题。
http://[domain]/file.axd?dateiname=mypdf.pdf