【问题标题】:return filename after save in WebAPi在 WebAPi 中保存后返回文件名
【发布时间】:2016-04-22 14:18:23
【问题描述】:

我正在使用 Web API 上传图像。

public IHttpActionResult UploadImage()
{
     FileDescription filedescription = null;
    var allowedExt=new string[]{".png",".jpg",".jpeg"};
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    if (Request.Content.IsMimeMultipartContent())
    {
       Request.Content.LoadIntoBufferAsync().Wait();
       var imgTask = Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
        {   
                MultipartMemoryStreamProvider provider = task.Result;
                var content = provider.Contents.ElementAt(0);
                Stream stream = content.ReadAsStreamAsync().Result;
                Image image = Image.FromStream(stream);
                var receivedFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                var getExtension = Path.GetExtension(receivedFileName);                      
                if(allowedExt.Contains(getExtension.ToLower())){
                    string newFileName = "TheButler" + DateTime.Now.Ticks.ToString() + getExtension;
                    var originalPath = Path.Combine("Folder Path Here", newFileName);
                    image.Save(originalPath);
                    var picture = new Images
                    {
                        ImagePath = newFileName
                    };
                    repos.ImagesRepo.Insert(picture);
                    repos.SaveChanges();
                    filedescription = new FileDescription(imagePath + newFileName, picture.Identifier); 
                }
        });

      if (filedescription == null)
       {
           return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message="some error msg."}));
       }
       else
       {
           return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, filedescription));
       }
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, new { message = "This request is not properly formatted" }));
    }
}

上面的代码我用来保存图像,但每次filedescription即使在图像成功保存之后。我在这里做错了什么。

我想在图像保存后返回文件描述。

【问题讨论】:

    标签: c# asp.net multithreading asp.net-web-api


    【解决方案1】:

    您以错误的方式使用了很多async 方法。永远不要调用 async 方法,然后等待它以同步方式完成(例如,使用 Wait()Result)。

    如果 API 公开了 async 方法,则为它提供 await,同时将调用方法变成 async 方法。

    filedescription 变量始终为空的原因是因为您在继续完成之前检查它。这确实是一个不好的做法:如果您需要一个作为 async 操作结果的值,那么您必须等待它完成,但在这种情况下,使用 await 关键字。

    这是调用async 方法并(异步)等待它们完成的正确方法:

    public async Task<IHttpActionResult> UploadImage()
    {
        FileDescription filedescription = null;
        var allowedExt = new string[] { ".png", ".jpg", ".jpeg" };
        var result = new HttpResponseMessage(HttpStatusCode.OK);
        if (Request.Content.IsMimeMultipartContent())
        {
            await Request.Content.LoadIntoBufferAsync();
            var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
    
            var content = provider.Contents.ElementAt(0);
            Stream stream = await content.ReadAsStreamAsync();
            Image image = Image.FromStream(stream);
            var receivedFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
            var getExtension = Path.GetExtension(receivedFileName);
            if (allowedExt.Contains(getExtension.ToLower()))
            {
                string newFileName = "TheButler" + DateTime.Now.Ticks.ToString() + getExtension;
                var originalPath = Path.Combine("Folder Path Here", newFileName);
                image.Save(originalPath);
                var picture = new Images
                {
                    ImagePath = newFileName
                };
                repos.ImagesRepo.Insert(picture);
                repos.SaveChanges();
                filedescription = new FileDescription(imagePath + newFileName, picture.Identifier);
            }
    
            if (filedescription == null)
            {
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message = "some error msg." }));
            }
            else
            {
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, filedescription));
            }
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, new { message = "This request is not properly formatted" }));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2014-11-20
      • 2017-06-04
      相关资源
      最近更新 更多