Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Angular 7 Http Post - Requires Complex Object?

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?

like image 425
aherrick Avatar asked Feb 06 '26 02:02

aherrick


1 Answers

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();
}
like image 169
er-sho Avatar answered Feb 07 '26 16:02

er-sho