Angular 2 http发布到.Net Core Web Api 500错误

时间:2017-03-14 18:34:35

标签: angular asp.net-web-api .net-core

我从angular 2 http向Web Api发送一个帖子请求,我得到500错误。我知道它的内部服务器错误,所以我在回复请求时有一些错误。但我无法弄明白。

页面组件

import { Component , OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { UserInformation } from '../../providers/user-information';
import { Employee } from './bruker';


@Component({
  selector: 'page-account-creation',
  templateUrl: 'account-creation.html',
  providers: [UserInformation]
})

export class AccountCreationPage implements OnInit {

  constructor( public navCtrl: NavController, private userInformation: UserInformation, private _fb: FormBuilder) {

  this.userInformation = userInformation;

}

   public myForm: FormGroup;
   bruker: Employee;



  ionViewDidLoad() {

  }

  ngOnInit() {


     // the short way
        this.myForm = this._fb.group({          
            Employee: this._fb.group({
                EmployeeID: ['', <any>Validators.required],
                FirstName: [],
                LastName: []               
            })
        });

     this.userInformation.getlogin().subscribe(
                data => console.log(data),
                err => console.log(err),
                () => console.log('Task Complete'));
  }

  onSubmit(model: Employee) {

     console.log(model);

    var x = this.userInformation.createuser(model).subscribe(
                data => console.log(data),
                err => console.log(err),
                () => console.log('Post Complete'));

  }



}

服务

 import { Injectable } from '@angular/core';
 import { Http, Response , Headers, RequestOptions, URLSearchParams} from '@angular/http';

    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/map';
    import { Employee } from '../pages/account-creation/bruker';

    @Injectable()
    export class UserInformation {

     private Url = 'http://localhost:63817/api/Bruker/';  // URL to web API
     headers: Headers;
     options: RequestOptions;

      constructor(private http: Http) {

      }

      createuser(bruker: Employee): Observable<Response>{

       console.log(JSON.stringify(bruker));



            let bodyString = JSON.stringify(bruker); // Stringify payload
            // let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
            // let options       = new RequestOptions({ headers: headers }); 


            return this.http.post(this.Url + "NyBruker", bodyString,{headers: this.getHeaders()})
            .map(response => response.json(),
              error => { debugger; });



      }

       private getHeaders(){
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
      }

    }

Rest API

using Crashy_Backends.Model;
using Crashy_Backends.Services;
using Crashy_Backends.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Routing;
using System.Net.Http;
using System.Net;

namespace Crashy_Backends.Controllers
{

    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    [Route("api/[controller]")]
    public class BrukerController : Controller
    {


        private IBrukerService _BrukerService;

        public BrukerController(IBrukerService BrukerService)
        {
            this._BrukerService = BrukerService;
        }


        [Route("NyBruker")]
        [HttpPost]
        public Employee NyBruker([FromBody]Employee bruker)
        {
            var x = bruker.EmployeeID;
            return bruker;
        }  

    }
}

2 个答案:

答案 0 :(得分:0)

关于您提供的信息,根据我自己的经验,问题很可能出在dependency injection。 您是否在IBrukerService中向依赖注入服务添加了Startup.csservices.AddTransient<IBrukerService, BrukerService>();

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection

答案 1 :(得分:0)

  1. 将请求的内容类型标头设置为application / json
  2. 确保您的Employee类定义匹配
  3. 非常确定#1会解决你的问题。 :)

    试试这个:

    return new Headers({ "X-Requested-With": "XMLHttpRequest", "Content-Type": 'application/json' });