1

I want to download a file with my controller :

  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;

    }

I did a test :

test

But it wasn't working because of the file extension .pdf For example when my fileName was equal to "test" it was working. But when I tried to put the ".pdf" it create issues.

So I changed my controller to this :

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;

    }

And now I just put my file name without extension in my url to download him.

But I think there is a better way to resolve this kind of issue. Can you give me advice or documentation. Because Didn't found anything about this problem.

guiz
  • 99
  • 1
  • 7
  • 2
    Does this answer your question? [Dots in URL causes 404 with ASP.NET mvc and IIS](https://stackoverflow.com/questions/11728846/dots-in-url-causes-404-with-asp-net-mvc-and-iis) – Ezra Feb 09 '20 at 14:14
  • I think the uri you're trying to call should be .../GetFile?filename=test.pdf – Zephire Feb 09 '20 at 14:20

1 Answers1

4

When a url contains a dot, IIS treats it as a physical path url.

A common solution for this is to define a custom handler in your web.config, for example:

<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>
Ezra
  • 529
  • 4
  • 5