Angular2 Service not passing JSON to WebAPI

≡放荡痞女 提交于 2019-12-25 07:36:20

问题


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)


来源:https://stackoverflow.com/questions/41574468/angular2-service-not-passing-json-to-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!