Send IFormFile to Web API using ViewModel in ASP.Net Core MVC

pandeygolu4200
 
on Sep 16, 2022 01:44 AM
551 Views

I have api which receives data and files (IForm) from my Ajax to controller.

Now how can i pass these data to my api which has FromForm type.

Please refer my code.

public async Task<IActionResult> DocumentAdd([FromForm] S3FileUpload documentAdd)
{
    try
    {
        //Firstly upload to S3
        ResponseList<Response> s3response = await _s3Utility.S3Upload(documentAdd, AWSFolder, _appSettings).ConfigureAwait(false);
 
        CrudOperations.Response response = new CrudOperations.Response();
        //On its success save in Db
        if (s3response.Status)
        {
            documentAdd.CreatedBy = User.Identity.Name;
            documentAdd.FileName = s3response.Data.FirstOrDefault().Data;
            response = await _providerRepository.DocumentAddAsync(documentAdd).ConfigureAwait(false);
        }
 
        if (!response.Status)
            return StatusCode(StatusCodes.Status400BadRequest, new { Status = false, Message = response.Message });
 
        response.Message = string.Format(CultureInfo.CurrentCulture, MessageHelper.ProviderDocumentAddedSuccess);
        return Ok(response);
    }
    catch (Exception ex)
    {
        Logger.AddErrorLog(_controller, "DocumentAdd", User.Identity.Name, ex, Newtonsoft.Json.JsonConvert.SerializeObject(documentAdd));
        return StatusCode(StatusCodes.Status500InternalServerError, new { Status = false, Message = String.Concat(ex.Message, MessageHelper.GenericException) });
    }
}

this is my api which receives data as class object

public class S3FileUpload
{
    [Required]
    public string UserID { get; set; }
    [Required]
    public long DocumentTypeID { get; set; }
    public string DocumentName { get; set; }
    public string? Description { get; set; }
    public string? DocumentPath { get; set; }
    public string? CreatedBy { get; set; }
    [MaxFileSize(MaxSize = 2 * 1024 * 1024, ErrorMessage = "Maximum allowed file size is 2MB.")]
    [ValidFileType(Extensions = new string[] { ".jpg", ".png" }, ErrorMessage = "Only .jpg and .png files are allowed.")]
    public List<IFormFile> Files { get; set; }
    public int? FileLimit { get; set; } = null;
    public long StateID { get; set; }
    public DateTime? IssueDate { get; set; }
    public DateTime? ExpirationDate { get; set; }
    public string? DocumentNumber { get; set; }
    public string? FileName { get; set; }
}

this is my class property of api

public IActionResult AddProviderDocument([FromForm] long DocumentTypeID, string DocumentName,string DocumentNumber,long StateID, DateTime IssueDate,DateTime ExpirationDate, List<IFormFile>? Files)
{
    ModelState.Remove("ManageProviderModel");
    if (ModelState.IsValid)
    {       
        ManageProviderDocumentModelCopy modeldoc = new ManageProviderDocumentModelCopy();
        modeldoc.UserID = Convert.ToString(TempData["ProviderId"]);
        modeldoc.DocumentTypeID = DocumentTypeID;
        modeldoc.DocumentName = DocumentName;
        modeldoc.DocumentNumber = DocumentNumber;
        modeldoc.StateID = StateID ;
        modeldoc.IssueDate = IssueDate;
        modeldoc.ExpirationDate = ExpirationDate;
        modeldoc.Files = (List<IFormFile>?)Files; 
 
        AccountApiCall accountApiCall = new AccountApiCall(Configuration["PrescriptionAPI"]);
        var Response = accountApiCall.PostAPIcall<GetProviderDetailModel>(modeldoc, "provider/documentadd", HttpContext.Request.Cookies["Token"].ToString());
        //return Json(Response.message);
        if (Response.status)
        {
            ViewBag.ProviderId = Response.data;
            return View();
        }
        else
        {
            ModelState.AddModelError("CustomError", Response.message);
            return View();
        }
    }
    else
    {
        return View();
    }
}

this is my code to call api , here data get converted to json and etting errror.

public static WebRequest GetRequest(string Method, string contentType, string endPoint, string Authorization = null, string Customer = null, string content = null)
{
     
    var request =(HttpWebRequest)WebRequest.Create(endPoint);
    request.Method = Method;
    request.ContentType = contentType;
    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    if (Authorization != null)
    {
        request.PreAuthenticate = true;
        request.Headers.Add("Authorization", "Bearer "+Authorization);
    }
    if (content != null)
    {
        var dataArray = Encoding.UTF8.GetBytes(content.ToString());
        request.ContentLength = dataArray.Length;
        var requestStream = request.GetRequestStream();
        requestStream.Write(dataArray, 0, dataArray.Length);
        requestStream.Flush();
        requestStream.Close();
    }
    return request;
}

This is my get request where it get fails. Now how can change code and pass my data to api.

Download FREE API for Word, Excel and PDF in ASP.Net: Download