Angular2 Service not passing JSON to WebAPI

2019-09-16 18:37发布

问题:

Trying to understand what I am doing wrong. I am trying to POST a JSON with a Angular Service to WebAPI2, once I pass it, I want to execute a stored procedure on the database with parameters taken from that JSON.

What happens here however instead:

  • The connection is successfully resolved to the Web Service - OK, I get a response from the server

  • The Debug.WriteLine on the Web Service outputs "VAR: 0 0" instead of the actual parameters in JSON

Not sure even where to start, is the problem with the Web Service not being able to handle the JSON sent or its Angular not passing the value correctly? Whats wrong?

ng2:

  updateKnowledge(knowledgeElement: KnowledgeElement) {
    this._action = "/post";

    this._url = CONFIGURATION.baseUrls.server + this._action;

    let headers = new Headers();
    headers.append('Content-Type','application/x-www-form-urlencoded; charset=utf-8');
    headers.append('Content-Type','application/json');

    this._http
        .post(this._url,JSON.stringify(knowledgeElement), { headers: headers})
                   .subscribe((res2) => {console.log('subscribe %o', res2)});
  }

export interface KnowledgeElement {
  knowledgE_USER_ID: number;
  knowledgE_NAME: string;
  knowledgE_DESCRIPTION: string;
  knowledgE_USER_SCORE: number;
}

Web Service:

        [HttpPost]
        [HttpGet]
        public IHttpActionResult Post([FromBody]getKnowledgeByUserId_Result value)
        {
            var dbContext = new KNOWH_TESTEntities();
            System.Diagnostics.Debug.WriteLine("VAR: " + value.KNOWLEDGE_USER_ID + " " + value.KNOWLEDGE_USER_SCORE);
            dbContext.updateKnowledge(value.KNOWLEDGE_USER_ID, value.KNOWLEDGE_USER_SCORE);

            return Ok();
        }

回答1:

Remove the first content-type and change the name in the service parameter equivalent the sent data.

let headers = new Headers();
headers.append('Content-Type','application/json');

this._http
    .post(this._url,JSON.stringify(knowledgeElement), { headers: headers})
               .subscribe((res2) => {console.log('subscribe %o', res2)});

And the Web Api

public IHttpActionResult Post([FromBody]getKnowledgeByUserId_Result knowledgeElement)