使用POST从Angular2发送时,Web API对象为null

时间:2017-06-01 04:05:20

标签: angular asp.net-web-api

我尝试通过从Angular2执行http发布到ASP.NET Web API端点来插入记录。在Angular中,对象包含数据,但是当它到达端点时,没有数据。它是null。你能通过这段代码看出我做错了什么吗?

角:

 public addBook (body: Object): Observable<Book[]> {
    let bodyString = JSON.stringify(body);  //stringify payload
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers });

    // post request to create new book
    return this._http.post(this.actionUrl,bodyString,options)
        .map((res:Response) => res.json()) 
        .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
}

ASP.NET Web API

  // POST: api/Books
  [System.Web.Http.HttpPostAttribute]
  [HttpOptions]
  [ResponseType(typeof(Book))]
  public async Task<IHttpActionResult> PostBook(Book book)
  {
     if (!ModelState.IsValid)
     {
        return BadRequest(ModelState);
     }

     db.Books.Add(book);
     await db.SaveChangesAsync();

     return CreatedAtRoute("DefaultApi", new { id = book.Id }, book);
  }

2 个答案:

答案 0 :(得分:0)

终于开始工作了。这是我使用的代码:

角:

public createService (url: string, param: any): Observable<any> {
    let body = JSON.stringify(param);
    let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8'})
    let options = new RequestOptions({ headers: headers });  // create a request option

    // post request to create new book
    return this._http
        .post('http://localhost:1234/api/Books/', body, options)
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'Server error')); 
}

Web API

// POST: api/Books
    [HttpPost]
    public async Task<IHttpActionResult> PostBook(Book book)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Books.Add(book);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = book.Id }, book);
    }

在Web Api中,WebApiConfig.cs我将这两行添加到Register方法中:

// port number of client
var cors = new EnableCorsAttribute("http://localhost:9000", "*", "*");
config.EnableCors(cors);

在Web.config中我添加了这些行:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
  </customHeaders>
</httpProtocol>

我还添加了nuget包:Microsoft.AspNet.WebApi.Cors

答案 1 :(得分:-1)

在Angular 2中使用http客户端时不需要JSON.stringify,似乎重复如下面的问题。

POST from Typescript to Web API API, unable to pass a JSON Object