Is it necessary to set the Content-Length in my response header?

21,882

Solution 1

Change the Content-Length line to the following:

Response.AddHeader("Content-Length", someByteArray.Length.ToString())

Solution 2

Your application SHOULD (scroll down to Content-Length) define it, however, it's not strictly required.

Here's a decent discussion of possible options.

Share:
21,882

Related videos on Youtube

Joseph
Author by

Joseph

Technical Director @ WarnerBros, Discovery

Updated on June 25, 2020

Comments

  • Joseph
    Joseph about 4 years

    I'm reviewing some legacy code and I've found a bug that causes the response to sit indefinitely.

    Here's the basic idea:

    Response.Content-Type = "application/octet-stream"
    Response.AddHeader("Content-Disposition", "attachment; filename" & someFileName)
    Response.AddHeader("Content-Length", someStoredLength)
    Response.BinaryWrite(someByteArray)
    Response.Flush()
    Response.End()
    

    The problem is that someStoredLength is much larger than the actual size of someByteArray, so the client just sits there waiting for the file download while the browser just spins.

    I'm contemplating just removing the AddHeader that specifies the content length, because when I do that everything seems to work fine, but I'm worried that I'm not understanding something.

    Is it ok for me to remove this AddHeader or should I figure out a better way to deal with this problem?

  • Joseph
    Joseph almost 15 years
    I was thinking of doing that too. I was wondering if that would be a good alternative. If I have a byte array will the Length property always give me the correct size?
  • Stephen
    Stephen almost 15 years
    Yes. The content-length header indicates the number of bytes in the content. Your content is an array of bytes, so you're good.
  • lxgr
    lxgr over 12 years
    The proposed solution in the linked article ("just set the length to some arbitrary value which will be likely too big") seems like a REALLY bad idea. Even if it doesn't break anything with current user agents, it undermines the whole concept of the "Content-length" header, and might break uncommon, but completely standards-compliant HTTP client libraries. If the size of the file is not known in advance, chunked transfer encoding should be used in all cases (and must be used if the connection is to be reused (keep-alive)).
  • paulkmoore
    paulkmoore over 10 years
    Direct link to Content-Length, see also HttpBis