Asp.net core webapi getting null value posted from Angular4 app

℡╲_俬逩灬. 提交于 2019-12-24 00:19:54

问题


I am new to Angular4 and in a situation to deliver the stuff quickly so have no time to learn it thoroughly so pardon if my question seems childish:

From my Asp.Net Web API I have Confirmemail API which has to be called from Angular4 application, looks like this:

Asp.net WebApi:

[HttpPost]
public async Task<object>ConfirmEmail([FromBody] string userid,[FromBody] string code)
{
}

In Angular4 Service API:

ConfirmEmail(userid,code)
{           
    let url =`api/account/ConfirmEmail`;
    let data= `userid=${userid}&code=${code}`;
    console.log(data);
    return this.http.post(url,data);
}

Here, I checked in console.log the data is coming properly, but at the webapi side I am finding these strings null. I tried removing [FromBody] but it didn't worked with me.

I am really clueless what is missing, it is almost one day preparing all these things but have not got any success. Do you guys have any workaround?


回答1:


For post data to your API from angular app try this in angular:

let url ="api/account/ConfirmEmail";

var userInfo = { "userid":userid, "code":code }
let content = JSON.stringify(userInfo);

let headers = new HttpHeaders(); 
headers.set("Content-Type", "application/json");

return this.http.post(url, content, { headers: headers, responseType: 'text'});

and in your API for receive your request body and deserialize this:

[HttpPost]
public async Task<object>ConfirmEmail([FromBody] UserInfo userInfo)
{

}

Public Class UserInfo
{
  public long userid {get; set;}
  public long code {get; set;}
}

For send your data in url you should use http get method like this:

Angular:

let Params = new HttpParams();

Params = Params.append("userid", userid);
Params = Params.append("code", code);

return this.http.get(url , { params: Params });

Web API:

[HttpGet]
public async Task<object>ConfirmEmail(string userid, string code)
{
}



回答2:


You can make an object of both userid and code and convert to string using JSON.stringify(data);

let url =`api/account/ConfirmEmail`;
let userObj = {'userid':userid,'code':code};
let data= JSON.stringify(userObj);
return this.http.post(url,data);

and access it as

[HttpPost]
public async Task<object>ConfirmEmail([FromBody] User userObj)
{

}


来源:https://stackoverflow.com/questions/48852189/asp-net-core-webapi-getting-null-value-posted-from-angular4-app

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