Last post Sep 03, 2019 12:45 AM by PatriceSc
Aug 28, 2019 02:49 AM|asplearning|LINK
Hello everyone, I have this peace of code to download file from the server:
private void downloadFile(string inputPath)
FileInfo file = new FileInfo(inputPath);
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
Response.ContentType = "application/octet-stream";
Now because I have repeated this code in many places, I would like to create a static method in a class so I only need to write it once. But when I tried to do it, Response is not recognized and I would need to do like this from this link https://www.codeproject.com/Questions/1036661/How-to-use-Response-Write-in-class-library
The link said it's a bad practice to do so. Could someone explain why? What is the right way to approach this?
Aug 28, 2019 05:42 AM|Yang Shen|LINK
As far as i know, Add above code will not cause any other bad influence. It's just like you do the using operation in your behind code.
As for the "bad pratice" in the link, i believe it's just a personal opinion on that specific case.
For more information about why you should add above code, you can refer to this thread.
Sep 03, 2019 12:45 AM|PatriceSc|LINK
The very first point is that a 3rd party developer may not realize immediately that a current http response is needed. It could be made obvious by having to pass an HttpResponse explicitly to your static method. A useful advice I saw once is to focus first
on what would be easier to write in your client code. For now it would give us:
HttpResponseExtensions.WriteAttachment(inputPath); // Static class
HttpResponseExtensions.WriteAttachment(Response,inputPath); // Same passing explicitly the response
At this point you could take advantage of
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods which is syntactic
sugar allowing to finally write Response.WriteAttachment(inputPath); and make your static WriteAttachment method look like an additional instance method on the response object.
Stop here but for completeness and depending on what does your ASPX page you could likely search later for "ASHX handlers"
(which allows to process an http request without going through the ASPX page lifecycle) or you could even consider adding MVC if this is not the only feature you could benefit from
(or just get some inspiration from its
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.filepathresult?view=aspnet-mvc-5.2 if you need to give more control later)