下面的c# mvc void Action客户端得到什么内容

下面的c# mvc void Action客户端得到什么内容

这是控制器里的代码

        public void Video(string pId)
        {
            //var pId = "HYNB_MP";
            var url = GetAerialUrl(pId);
            var filePath = Urlconvertorlocal(url);
            //这里需要获取全路径 如:D:\project\images\video\products\video.mp4
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (fileInfo.Exists == true)
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();

                //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileInfo.Name));
                Response.AddHeader("Content-Length", "" + fileInfo.Length.ToString());
                Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
        }

运行成功后会成功播放视频,但想不通video方法明明时void无返回值的,但为何设置了返回值后还是会正常返回

因为题主调用了Response.BinaryWrite输出内容。和方法什么返回值没关系。如果方法设置了返回值,那么要在最后返回和方法定义的类型一样的数据,要不编译时会报错。
mvc的直接定义返回值为ActionResult,return File(filePath ,"application/octet-stream");就行了,不用搞那么麻烦。然后mvc会自动调用Response对象输出需要的信息,只是mvc做了包装,不需要调用Response相关方法输出。
如果题主学过webform,就很好理解Response.Write作用了。webform很多处理方法都是void类型的,特别ashx处理文件,都是用Response获取和输出内容到客户端。

这段代码的目的是向客户端发送一个视频文件,具体的流程是这样的:

  1. 根据参数pId获取视频文件的URL。
  2. 将URL转换为本地文件路径。
  3. 检查文件是否存在。
  4. 如果存在,读取文件的内容并写入Response中。
  5. 设置Response的头信息,包括Content-Length、Content-Transfer-Encoding、Content-Type。
  6. 输出Response。
  7. 关闭Response。
    客户端接收到的内容是一个二进制文件,根据Response的Content-Type和Content-Encoding确定其类型和编码方式。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632