I am learning Angular right now, and i am trying to make a POST into a API in asp.net core. I went to the startup and made the cors since they were giving me problems. Now, my problem is an error 415, i don´t know why is saying the payload is not supported it's making 0 sense to me. My API function is this:
[HttpPost]
public IActionResult register([FromBody] RegisterModel registro)
{
Cristais cristal = new Cristais { ID = "4", Cristal = "Zombie44" };
_context.Cristais.Add(cristal);
_context.SaveChanges();
Utilizadores utilizador = new Utilizadores();
utilizador.ID = Guid.NewGuid().ToString();
utilizador.Comida = 100;
utilizador.Gold = 1000;
utilizador.ID_Cristal = "4";
utilizador.Email = registro.email;
utilizador.NickName = registro.nickName;
utilizador.Password = registro.password;
_context.Utilizadores.Add(utilizador);
_context.SaveChanges();
Console.WriteLine(_context.Utilizadores.Where(p=> p.ID_Cristal=="4"));
return Ok(_context.Utilizadores.ToList());
}
And then i tried my post in angular:
registar() {
console.log(this.utilizador);
console.log(config.Urlsite);
this.httpClient.post(config.Urlsite + "Utilizador/register",this.utilizador, {headers: new HttpHeaders({'Content-Type': 'json'})} ).subscribe((resultado)=>{
console.log(resultado);
}, (casoErro)=>{
console.log(casoErro);
})
}
utilizador is a variable that contains information about a user in json form something like:
{ "nickName": "Ricardo", "password": "Zombie33", "email": "[email protected]" }
Also, registro in the API function is a model with 3 strings...
If i try this in postman it all goes well.. I dont understand why i can´t do it in angular All help is appreciated, thanks! :)
[EDIT] I just tried to place [EnableCors("StratGameWebSiteAngular")] on the API function, and than i got error 500.. i am lost right now
my problem is an error 415, i don´t know why is saying the payload is not supported
In your Angular client side code, we can find that you set {headers: new HttpHeaders({'Content-Type': 'json'})}
, which cause the issue.
You can set Content-Type
with application/json
, like below.
this.httpClient
.post(
config.Urlsite + "Utilizador/register",
this.utilizador,
{ headers: new HttpHeaders({ "Content-Type": "application/json" }) }
)
.subscribe(
resultado => {
console.log(resultado);
},
casoErro => {
console.log(casoErro);
}
);
Test Result