0

剛開始使用ASP.Net 4.5和我的API總是返回內部服務器錯誤。異步上傳內部服務器錯誤500 mvc 5

上傳API

public class UploadController : ApiController 
{ 
    public async Task<HttpResponseMessage> PostFile() 
    { 
     if (!Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 

     string root = HttpContext.Current.Server.MapPath("~/App_Data/uploads/"); 
     var provider = new CustomMultipartFormDataStreamProvider(root); 

     try 
     { 
      await Request.Content.ReadAsMultipartAsync(provider); 

      return Request.CreateResponse(HttpStatusCode.OK); 
     } 
     catch (System.Exception e) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 

}

我的控制器

var message = new HttpRequestMessage(); 
    var content = new MultipartFormDataContent(); 
    message.Method = HttpMethod.Post; 
    message.Content = content; 
    message.RequestUri = new Uri("http://localhost:12345/api/upload/"); 

    var client = new HttpClient(); 
    client.SendAsync(message).ContinueWith(task => 
    { 
      var result = task.Result.ReasonPhrase; 
      if (task.Result.IsSuccessStatusCode) 
      { 
        //do something 
      } 
    }); 

文件被保存在位置(/ App_Data文件/上傳/),但爲什麼狀態代碼總是500?

請賜教。感謝

+0

[這裏](http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0)是文件上傳示例。當你得到這個錯誤時,你能告訴更多嗎? –

+0

該鏈接是同步上傳的示例。我的實現是異步的。 – Awoi

+0

有一刻我會發布異步的例子。 –

回答

0

下面是工作控制器的一部分:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Create(Product product, HttpPostedFileBase file) 
    { 
     if (!ModelState.IsValid) 
      return PartialView("Create", product); 
     if (file != null) 
     { 

      var fileName = Path.GetFileName(file.FileName); 
      var guid = Guid.NewGuid().ToString(); 
      var path = Path.Combine(Server.MapPath("~/Content/Uploads/ProductImages"), guid + fileName); 
      file.SaveAs(path); 
      string fl = path.Substring(path.LastIndexOf("\\")); 
      string[] split = fl.Split('\\'); 
      string newpath = split[1]; 
      string imagepath = "Content/Uploads/ProductImages/" + newpath; 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       file.InputStream.CopyTo(ms); 
       byte[] array = ms.GetBuffer(); 
      } 
      var nId = Guid.NewGuid().ToString(); 
      // Save record to database 
      product.Id = nId; 
      product.State = 1; 
      product.ImagePath = imagepath; 
      product.CreatedAt = DateTime.Now; 
      db.Products.Add(product); 
      await db.SaveChangesAsync(); 
      TempData["message"] = "ProductCreated"; 

      //return RedirectToAction("Index", product); 
     } 
     // after successfully uploading redirect the user 
     return Json(new { success = true }); 
    } 
+0

注意:您的上傳文件夾的權限已更改:IIS_IUSRS –

+1

我認爲問題不在於實現的異步部分。它成功地將文件保存在服務器上,但它總是進入catch塊。我不知道爲什麼。 – Awoi

+0

請原諒我,真的不知道爲什麼,因爲我使用ree返回方法,所以爲什麼它會捕獲真正有趣的。 –