I'm trying to do a basic HTTP Post to an ASP.NET Core back end.
Angular:
var parms = {
userRoles: ['User', 'Worker'],
email: '[email protected]'
};
this.http.post('/UserRole/SaveUserRoles', parms)
.subscribe(result => { });
Controller:
[HttpPost]
public async Task<IActionResult> SaveUserRoles([FromBody]string[] userRoles, string email)
{
return Ok();
}
My parameters are showing null. I can get this working by creating a complex object C# side, but that's not what I want to do. I don't need an object just for 2 parameters.
What's missing here?
You have to set proper header for your request like,
var postData = {
userRoles: ['User', 'Worker'],
email: '[email protected]'
};
const headers: HttpHeaders = new HttpHeaders();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('/UserRole/SaveUserRoles', postData, { headers: headers })
.subscribe(result => {
});
And for your controller side,
I don't need an object just for 2 parameters.
But this is a good practice to catch all your posted data in the model or c# object.
So here I create a sample class.
class PostData
{
public string[] userRoles { get; set; }
public string email { get; set; }
}
[HttpPost]
public async Task<IActionResult> SaveUserRoles([FromBody]PostData postData)
{
return Ok();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With