简体   繁体   English

How do i send an object from Angular to an Asp.net Web Api?

[英]How do i send an object from Angular to an Asp.net Web Api?

I have the exception in my Web Api我的 Web Api 有异常

Object reference not set to an instance of an object. Object 引用未设置为 object 的实例。

The data in the object is printed on to the console but it is not passed to the Api Controller. object 中的数据打印到控制台,但不会传递给 Api Controller。 The object ae s "null" object ae s "null"

This is my controller:这是我的 controller:

[Route("api/AddMovie")]
[HttpPost]
public int AddMovie([FromBody]Movie movie)
{
   int check = objMovie.AddMovie(movie);
   return check;
}

AddMovie is the function i created to store data in database. AddMovie 是我为在数据库中存储数据而创建的 function。

This is my component:这是我的组件:

import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { slideInOutAnimation } from 'src/app/animations';
import { Movie } from 'src/app/movie';
import { NgxSpinnerService} from 'ngx-spinner';
import { MovieServiceService } from 'src/app/Service/movie-service.service';
import { HttpClient } from '@angular/common/http';
import { formatNumber } from '@angular/common';

@Component({
  selector: 'app-addmovie',
  templateUrl: './addmovie.component.html',
  styleUrls: ['./addmovie.component.css'],
  // make slide in/out animation available to this component
  animations: [slideInOutAnimation],

  // attach the slide in/out animation to the host (root) element of this component
  // tslint:disable-next-line: no-host-metadata-property
  host: { '[@slideInOutAnimation]': '' }
})
export class AddmovieComponent implements OnInit {

  // tslint:disable-next-line: new-parens
  movie = new Movie;
  fileData: File = null;
  addMovieForm: FormGroup;


  constructor( 
    private spinner: NgxSpinnerService,
    public fb: FormBuilder,
    private http: HttpClient,
    public movieService: MovieServiceService) {
    this.addMovieForm = this.fb.group ({
      movieName: new FormControl('', [Validators.required, Validators.minLength(1)]),
      releaseDate: new FormControl('', [Validators.required]),
      releaseYear: new FormControl('' , [Validators.required]),
      certification: new FormControl('' , [Validators.required]),
      runtime: new FormControl('', [Validators.required]),
      rating: new FormControl('', [Validators.required, Validators.max(10)]),
      moviePlot: new FormControl('', [Validators.required, Validators.minLength(1)]),
      cast: new FormControl('', [Validators.required, Validators.minLength(1)]),
      imageName: new FormControl('', [Validators.required])
    });
  }

  ngOnInit() {
  }

  onFileSelect(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.addMovieForm.get('imageName').setValue(file);
    }
  }
  public onSubmit() {
    debugger;
    // tslint:disable-next-line: prefer-const
    let movieForm = this.addMovieForm.value;
    this.movie.movieName = movieForm.movieName;
    this.movie.releaseDate = movieForm.releaseDate;
    this.movie.releaseYear = movieForm.releaseYear;
    this.movie.certification = movieForm.certification;
    this.movie.runtime = movieForm.runtime;
    this.movie.review = movieForm.rating;
    this.movie.moviePlot = movieForm.moviePlot;
    this.movie.cast = movieForm.cast;
    this.movie.imageName = movieForm.imageName;
    console.log(this.movie);
    this.http.post('http://localhost:50686/api/AddMovie', this.movie).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
}
}

You are invoking the api call without any header.您正在调用没有任何 header 的 api 调用。 Try the following尝试以下

const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
this.http.post('http://localhost:50686/api/AddMovie', this.movie, httpOptions)
.subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );

The error says that your object Movie is null.该错误表明您的 object Movie是 null。 It means that you haven't initialized your object yet or you have set it to null.这意味着您尚未初始化 object,或者您已将其设置为 null。 In this case you can do the following,在这种情况下,您可以执行以下操作,

  1. To initialize the object before you use it,要在使用 object 之前对其进行初始化,

     Movie movie = new Movie();
  2. Check for null before you use the object instance,在使用 object 实例之前检查 null,

     public int AddMovie([FromBody]Movie movie) { if (movie != null) { // Do something with movie } }
  3. Handle the null and throw a suitable exception,处理null并抛出合适的异常,

     public int AddMovie([FromBody]Movie movie) { if (movie == null) { throw new Exception("Custom exception message"); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM