1

I'm trying to insert a record by doing an http post from Angular2 to an ASP.NET Web API endpoint. In Angular the object contains data, but when it gets to the endpoint there's no data. It is null. Can you see what I'm doing wrong by this code?

Angular:

 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 Answers 2

0

Finally got it to work. Here's the code I used:

Angular:

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

In Web Api, WebApiConfig.cs I added these two lines to the Register method:

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

In Web.config I added these lines:

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

I also added the nuget package: Microsoft.AspNet.WebApi.Cors

Sign up to request clarification or add additional context in comments.

Comments

-1

JSON.stringify is not required when using http client in Angular 2, seems duplicated as the below question.

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

1 Comment

Not quite the same. That example uses a Promise instead of an Observable. Might be the same issue though, I'm not sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.