WebAPI - File download checksum?

2019-09-16 14:46发布

问题:

I'm currently downloading a file from my Web API using a C# RestClient. This is my current code for returning a file from the Web API part:

[HttpGet]
public HttpResponseMessage Generate()
{
var stream = new MemoryStream();
// processing the stream.

var result = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
    new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
    FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
    new MediaTypeHeaderValue("application/octet-stream");

return result;
}

Taken from this: How to return a file (FileContentResult) in ASP.NET WebAPI

My question is then, how can i validate that the file is downloaded correctly - can i somehow provide an MD5 checksum on the ByteArray and check this in the RestClient, or is this complete unnecessary?

回答1:

You would generate a hash of the file, add it as a response header and verify when the download completes within the client.

This would only make sense if you think there is a chance of corruption of the data within your stream or network issues outside the ability of TCP error correction to handle.

How necessary this is is a judgement call, see Why is it good practice to compare checksums when downloading a file? for a discussion. (Considering the hash & data originate from the same place in the same response, the security considerations don't really apply)