在这种情况下,Asp.Net WebApi

时间:2019-10-03 13:37:39

标签: asp.net-web-api

当我尝试在WebApi中实现相同的代码时,我有一个代码可以在C#网站中下载文件,但出现异常“请求在此上下文中不可用”。请在这里帮助我。我还添加了Page名称空间。

只要它在Downloaddocument Function的抛出异常中命中了ResponseFile函数,

代码:

 public void DownloadDocument(string fileName)
    {
        string fileUrl = string.Empty;
        try
        {
            fileUrl = "The url we want to download from";
            if (!File.Exists(fileUrl))
            {
                fileUrl = fileUrl.Replace(" ", "+");
            }
            if (File.Exists(fileUrl))
            {
                Page.Response.Clear();

                bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
                if (!success)
                {
                  Response.Write("Downloading Error!");
                }
                else
                {
                    Page.Response.End();
                }
            }
            else
            {
                 Alert.ShowAlert("File Not Found.");

            }
        }
        catch (Exception ex)
        {
            if (ex is System.Threading.ThreadAbortException)
            {

            }
            else
            {
                new ExceptionHandler(ex,"");
            }
        }
    }

    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            FileInfo FileInfo = new FileInfo(_fullPath);

            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;
                int maxCount = 0;
                int pack = 0;
                if (FileInfo.Length >= 102400)
                {
                    pack = 102400;
                    maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
                }
                else
                {
                    pack = Convert.ToInt32(FileInfo.Length);
                    maxCount = 1;
                }
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch (Exception e)
            {
                new ExceptionHandler(e, "Download Error");
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch (Exception e)
        {
            // throw new ExceptionHandler(e, "Download Error");
        }
        return true;
    }

另外,请告知我是否需要更多代码。

0 个答案:

没有答案