Search code examples
angularasp.net-corehttp-postasp.net-core-webapi

How to post a string value from Angular 8 to .NET core Web API?


I cannot post a simple string value to my WebApi and I get a 415 error. What's the correct syntax to make this happen? Thanks!

createRole(name: string) {
    var fullUri = this.baseUri;
    fullUri += 'api/role/CreateRole';

    return this.http.post(fullUri, name);
}
[HttpPost("CreateRole")]
public async Task<IActionResult> CreateRoleAsync([FromBody]string name)
{
    //...

}

Solution

  • Use [FromForm] attribute instead of [FromBody] attribute. And apply [ApiController] attribute to your controller.

    [HttpPost("CreateRole")]
    public async Task<IActionResult> CreateRoleAsync([FromForm]string name)
    {
        //...
    
    }
    

    It will work if you post name as FormData or using Form tag. Because [FromForm] gets values from posted form fields.

    Another solution is post name as object and make a model / DTO

    public class SaveModel 
    {
       public string Role {get; set;}
    }
    [HttpPost("CreateRole")]
    public async Task<IActionResult> CreateRoleAsync([FromBody] SaveModel model)
    {
        //...
    
    }