Reputation: 169
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?
Upvotes: 4
Views: 3652
Reputation: 6106
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)
{
}
Upvotes: 1
Reputation: 222582
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)
{
}
Upvotes: 2