2017-06-01 76 views
0

我試圖通過從Angular2向http Web API端點執行http post來插入記錄。在Angular中,對象包含數據,但是當它到達端點時,沒有數據。它是空的。你能通過這段代碼看到我做錯了什麼嗎?使用POST從Angular2發送時Web API對象爲空

角:

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); 
    } 

回答

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); 
    } 

在網絡API,WebApiConfig.cs我將這兩行的註冊方法:

// 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