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:-
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:-
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:-
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:-
[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