将同步调用更改为异步等待(异步)MvC控制器

时间:2017-06-19 16:38:40

标签: asp.net-mvc asynchronous async-await

我是C#Asp.net mvc异步编程的新手。我需要将vidoe上传到我的服务器,但是当我上传视频时视频上传被锁定。我无法并行完成另一项任务。我试过这样但是没有用。

 public async Task<ActionResult> upload()
  {
       if (Request.Files.Count > 0)
            {
                int chunk = Request["chunk"] != null ? 
           int.Parse(Request["chunk"]) : 0;
                string fileName = Request["name"] != null ? Request["name"] : 
               string.Empty;

                string upath = "";
                if (Request.Headers["UName"] != null)
                    upath = Request.Headers["UName"].ToString();

                //if (CloudSettings.EnableCloudStorage && upath != "")
                //    _fileName = upath.Substring(0, 3) + "-" + _fileName; //  void duplication in cloud storage


                long AlbumID = 0;
                if (Request.Headers["MediaID"] != null)
                    AlbumID = Convert.ToInt64(Request.Headers["MediaID"]);

                string uploadPath = "";
                // default path
                if (upath == "")
                    uploadPath = UrlConfig.Published_Video_Path(); // direct upload to published area
                else
                    uploadPath = UrlConfig.Published_Video_Path(upath); // source video path

                FileStream fs;
                using (fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    byte[] buffer = new byte[Request.Files[0].InputStream.Length];
                   await Request.Files[0].InputStream.ReadAsync(buffer, 0, buffer.Length);

                   await  fs.WriteAsync(buffer, 0, buffer.Length);
                }
                string url = "";
                string filetype = System.IO.Path.GetExtension(fileName);
                string fileIndex = fileName.Replace(filetype, "");
                string elementid = UtilityBLL.ReplaceSpaceWithHyphin(fileIndex);
                //eturn fileName; // "Success";
                return this.Content("{\"jsonrpc\" : \"2.0\", \"result\" : \"OK\", \"id\" : \"id\", \"fname\" : \"" + fileName + "\", \"url\" : \"" + url + "\", \"filetype\" : \"" + filetype + "\", \"filename\" : \"" + fileName + "\",  \"fileIndex\" : \"" + fileIndex + "\", \"eleid\" : \"" + elementid + "\"}", "text/plain");

            }
            else
            {
                return this.Content("failed", "text/plain");
            }
 }

0 个答案:

没有答案