【问题标题】:File name with extension in url as a parameter [duplicate]url中带有扩展名的文件名作为参数[重复]
【发布时间】:2020-05-25 00:11:04
【问题描述】:

我想用我的控制器下载一个文件:

  public HttpResponseMessage GetFileConverted(string fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            return Request.CreateResponse(HttpStatusCode.BadRequest);

        string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");

        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(new FileStream((filePath + fileName), FileMode.Open, FileAccess.Read));
        response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return response;

    }

我做了一个测试:

但由于文件扩展名为 .pdf,它无法正常工作 例如,当我的文件名等于“测试”时,它正在工作。但是,当我尝试放入“.pdf”时,它会产生问题。

所以我把我的控制器改成了这个:

public HttpResponseMessage GetFile(string fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            return Request.CreateResponse(HttpStatusCode.BadRequest);

        string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");

        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(new FileStream((filePath + fileName + ".pdf"), FileMode.Open, FileAccess.Read));
        response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return response;

    }

现在我只是把我的文件名不带扩展名放在我的网址中下载他。

但我认为有更好的方法来解决此类问题。你能给我建议或文件吗?因为没有发现任何关于这个问题的信息。

【问题讨论】:

标签: c# asp.net asp.net-mvc visual-studio asp.net-web-api


【解决方案1】:

当 url 包含点时,IIS 将其视为物理路径 url。

一个常见的解决方案是在您的 web.config 中定义一个自定义处理程序,例如:

<system.webServer>
  <handlers>
    <add name="ApiURIs-ISAPI-Integrated-4.0"
        path="/downloads/*"
        verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
        type="System.Web.Handlers.TransferRequestHandler"
        preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 2018-03-02
    • 2011-12-28
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多