Click here to Skip to main content
15,922,007 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,
I created a .net core(v3) Web API and an Angular project, so I trying to send an object which will contain a file and others data (like name, duration etc..).

My Angular component code:-
JavaScript
 saveMovie() {
    this.submitted = true;
    if (this.movieFormGp.invalid) {
      return;
    }
    this.movieFormGp.patchValue({ rating: this.currentRate });
    let movieData= new FormData();
    movieData.append("name", this.movieFormGp.get('name').value);
    movieData.append("Duration", this.movieFormGp.get('duration').value);
    movieData.append("Review", this.movieFormGp.get('review').value);   
    movieData.append("GenresIDs",JSON.stringify( [4,6]));   
movieData.append("PosterImg",this.posterImage);

console.log(movieData);
    this.movieService.addMovie(movieData).subscribe((resp)=>{
      console.log(resp);
    },error=>{
      console.error(error);
    })
  }


Angular Servie code:-
JavaScript
 headers={
    headers: new HttpHeaders({
      'enctype': 'multipart/form-data',
      'Accept': 'application/json'
    })
};
addMovie(movie:any)
  { 
    return this.http.post<any>(environment.baseAPIUrl+'Movies/addMovie',movie);
  }


.net Model:-
C#
public class CreateMovieDTO
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public string Duration { get; set; }
        public string Review { get; set; }       
        public List<int> GenresIDs { get; set; }
        public bool IsFavorite { get; set; }
        public DateTime AddedOn { get; set; }       
        public IFormFile PosterImg { get; set; }
        public CreateMovieDTO()
        {
            GenresIDs = new List<int>();
        }
    }


API Method:-
C#
 [Route("api/[controller]")]
    [ApiController]
    [AllowAnonymous]

    public class MoviesController : ControllerBase
    {
 private readonly IMovieRepository _repository;
        private readonly DataContext _context;

        public MoviesController(IMovieRepository repository, DataContext context)
        {
            _repository = repository;
            _context = context;
        }
 [HttpPost("addMovie")]
        public async Task<IActionResult> AddMovie([FromForm] CreateMovieDTO movieDTO)
        {
            try
            {
                if (movieDTO == null)
                {
                    return BadRequest("object is null");
                }
                var reqFile = Request.Form.Files;
                var movie = new Movie()
                {                   
                    Name = movieDTO.Name,                   
                    Duration = movieDTO.Duration,
                    Review = movieDTO.Review,
                };

                foreach (var item in movieDTO.GenresIDs)
                {
                    var genre = await _repository.GetGenre(item);
                    movie.MovieGenres.Add(new MovieGenres { Genres = genre, Movie = movie });
                }
                _repository.Add<Movie>(movie);
                var response = await _repository.SaveAll();
                return Ok(response);
            }
            catch (Exception exp)
            {

                return BadRequest(exp);
            }
        }
}


What I have tried:

If I send only JSON data without file and [FromBody] then it works fine but if I add the file with formdata then at the API method all properties are null though its hit the APi method.
if I use [FromForm] with formdata then it doesn't hit the API method but the Network call its showing Request Status 200

Please help..

Thanks in advanced.
Jayanta
Posted
Updated 6-Feb-23 14:34pm

WebAPI built-in formatters only support the following media types: application/json, text/json, application/xml, text/xml and application/x-www-form-urlencoded


Now, in your context, you are trying to do:
API method that has to send form-data format to the server

This means:
1. You need to make sure the server accepts multiple format as content type payload.
2. Once you are sure of that, then for multipart/form-data, which is what you are sending, look at ASP.NET WebApi: MultipartDataMediaFormatter[^]

Try out.
 
Share this answer
 
v3
Comments
JayantaChatterjee 15-Aug-20 23:42pm    
Thanks,
I have verified the points which you mentioned. Its looks good from my application.

In my scenario I am adding extra header with http request from angular. so after removing that header part from http request its started working.
Sandeep Mewara 16-Aug-20 2:58am    
Good to know your issue is resolved! :thumbsup:
I have the same issue not resolved yet.

My API Code:

HttpPut("updateThemeDetail/{whiteLabelId}")]
public async Task<IActionResult> UpdateThemeDetail([FromForm]TenantThemeSetUpInput item, string whiteLabelId)
{............


Model DTO:

public class TenantThemeSetUpInput
 {
     public string? ThemePrimaryColor { get; set; }
     public string? ThemeAccentColor { get; set; }
     public string? ThemeName { get; set; }
     public IFormFile? LoginBanner { get; set; }
     //public IFormFile? PageBanner { get; set; }
     public IFormFile? SecondaryLogo { get; set; }
     public IFormFile? PrimaryLogo { get; set; }

 }


The angular part is the same as mentioned in the question.
I am getting API method all properties are null

Please assist me in resolving this issue.
 
Share this answer
 
v2
Comments
Richard Deeming 7-Feb-23 4:27am    
Your question is not a "solution" to someone else's question.

If you want to ask a question, then ASK A QUESTION[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900