WebApi HttpGet路由未返回HttpResponseMessage的Content-Length响应头

时间:2015-11-12 21:27:14

标签: asp.net-web-api2 ftpwebrequest

我有一个WebApi端点,它获取一个mp4的FTP文件,然后返回它。出于某种原因,Content-Length响应标头未设置,我怀疑这导致我的html5视频没有控件正常工作,因为用户无法搜索。

HTML:

<video controls src="api/my-ftp-file.mp4"></video>

的WebAPI:

[Route("api/{fileName}")]
[HttpGet]

public HttpResponseMessage FtpFile(string fileName)
{
    var credentials = new NetworkCredential("...", "...");

    var fullFilePath = "ftp://my-ftp-server/" + fileName;

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(fullFilePath);
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    request.Credentials = credentials;
    var response = (FtpWebResponse)request.GetResponse();
    var stream = response.GetResponseStream();

    // get content length (since response.ContentLength from above is -1)
    FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(fullFilePath);
    request2.Method = WebRequestMethods.Ftp.GetFileSize;
    request2.Credentials = credentials;
    var response2 = (FtpWebResponse)request2.GetResponse();
    var contentLength = response2.ContentLength; // this DOES provide a value

    var ret = new HttpResponseMessage(HttpStatusCode.OK);
    ret.Content = new StreamContent(stream);
    ret.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4");
    // I've also tried ret.Content.Headers.ContentLength = contentLength
    ret.Content.Headers.Add("Content-Length", contentLength.ToString());

    return ret;
}

我的html5视频标签播放视频,如果你拖动自动收录器寻找视频中的另一个点,没有任何反应。我怀疑是b / c我的Chrome网络标签中的内容长度丢失了:

enter image description here

为什么内容长度不随请求一起发送?

1 个答案:

答案 0 :(得分:0)

因为您将回复发送为&#34; chunked&#34; (转移编码:chunked)。 见wikipedia: transfer encoding