Home > database >  Response from controller class
Response from controller class

Time:03-01

I have a controller class that someone at work wrote that contains a method that looks like this.

(obviously it's not the full code, just the part I find confusing). It's part of a ASP.Net Core project.

var memoryStream = new MemoryStream();
var result = new HttpResponseMessage(HttpStatusCode.OK);

using (var stream = System.IO.File.OpenRead(newZipPath))
{
    stream.CopyTo(memoryStream);
    result.Content = new ByteArrayContent(memoryStream.ToArray());
}

return File(memoryStream.ToArray(), "application/zip");

Now I'm not that good at C# but it feels like that "result" variable is not going to be sent anywhere or used? Am I correct or does ASP.Net Core have some magic way of sending this result as well as the one in the return statement.

CodePudding user response:

That's correct. There doesn't appear to be any point in the result variable, ASP.Net MVC (both Framework and Core versions) will generate an appropriate FileResult from File(memoryStream.ToArray(), "application/zip");.

You could go one step further and really reduce this code even more:

using (var stream = System.IO.File.OpenRead(newZipPath))
{
    return File(stream, "application/zip");
}

No need to create a second MemoryStream ar convert it to a byte array.

  • Related