0

I want to upload and save a file along with other user input data having datatype int,string and datetime. I would like save the file to the hard-drive and save the path and other input data in the SQL Server database table. I am getting AggregateException whenever I am trying to do both together. I am new to ASP.NET MVC and Web API.

Below is my action method in ASP.NET MVC project.

public ActionResult AddOrEdit(mvcCandidate cn)
{
    if (cn.ID == 0)
    {
        if (cn.cvFile.ContentLength != 0)
        {
            string filename = Path.GetFileNameWithoutExtension(cn.cvFile.FileName);
            string extension = Path.GetExtension(cn.cvFile.FileName);
            filename = filename + DateTime.Now.ToString("yymmssff") + extension;
            cn.path = "~/Uploads/" + filename;
            filename = Path.Combine(Server.MapPath("~/Uploads/"), filename);
            cn.cvFile.SaveAs(filename);
        }
        else
            cn.path = "";
        try
        {
            HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Candidates", cn).Result;
        }
        catch (AggregateException ex)
        {
            var ch = ex.Message;
            return null;
        }         
    }
}

And this is the action method in WebAPI project

public IHttpActionResult PostCandidate(Candidate candidate)
{
    db.Candidates.Add(candidate);
    db.SaveChanges();
    return CreatedAtRoute("DefaultApi", new { id = candidate.ID }, candidate);
}

The model class is as below:

public class mvcCandidate
{
    public int ID { get; set; }
    [Display(Name="Name")]
    public string Name { get; set; }
    [Display(Name = "Address")]
    public string Adress { get; set; }    
    [Display(Name = "Date Of Birth")]
    [DataType(DataType.Date)]
    public Nullable<System.DateTime> DOB { get; set; }
    public string PIN { get; set; }
    public Nullable<int> CompanyID { get; set; }
    [Display(Name = "CV")]
    public string path { get; set; }
    public HttpPostedFileBase cvFile { get; set; }           
    public virtual mvcCompany Company { get; set; }
}
2
  • Mmm...so PostAsJsonAsync actually calls your PostCandidate method? Commented Apr 24, 2018 at 17:23
  • yes.MVC and WepAPI are two seperate projects in same solution.Globalvariables is the static class setting httpclient details. Commented Apr 24, 2018 at 17:43

1 Answer 1

1

I had struggled a lot to save file with data when dealing with Web API, so I managed to solve this problem by taking the properties and the file from the current HttpContext, I know using binding is much more easier, however this way worked for me, so the controller (API controller code) for saving file is:

    [HttpPost]
    public IHttpActionResult SaveFileWithData()
    {
        try
        {
            var httpRequest = HttpContext.Current.Request;
            #region Get entity data
            var entity = new EntityClass();
            entity.Name = httpRequest.Params["name"];

            //here you put the saving code into entity framework aka Context.Entity.Add(entity); Context.SaveChanges();

            #endregion

            if (httpRequest.Files.Count > 0)
            {
                var myFile = httpRequest.Files[0];

                var filePath = HttpContext.Current.Server.MapPath($"~/Files/{ myFile.FileName}");
                //Set the file into server
                myFile.SaveAs(filePath);
            }
            return Ok();
        }
        catch (Exception ex)
        {
            return InternalServerError();
        }
    }

And when submitting the data from the client I had used Multipart form as following:

Test API using RESTFull client

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.