0

Just started using ASP.Net 4.5 and my API always returns Internal Server Error.

Upload 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);
        }
    }

}

My Controller

    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
            }
    });

The files are saved in the location (/App_Data/uploads/) but why is the status code always 500?

Please enlighten me. Thanks

Awoi
  • 46
  • 8

1 Answers1

0

Here is part of working controller:

[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 });
    }
Archil Labadze
  • 4,049
  • 4
  • 25
  • 42
  • NOTE: You have change permisions for your uploads folder: IIS_IUSRS – Archil Labadze Jun 10 '16 at 00:37
  • 1
    I don't think the problem's with the async part of the implementation. It successfully saves the files on the server but it always enters the catch block. I don't know why. – Awoi Jun 10 '16 at 00:39
  • Pardon me, realy don't know why, as I ree return method is used so why it goes to catch realy interesting. – Archil Labadze Jun 10 '16 at 00:44