I have a .Net5 Webapi with a simple controller and a HttpPost-Action:
[ApiController]
[Route("[controller]")]
public class UploadController : ControllerBase
{
[HttpPost]
[Route("codeisvalid")]
public bool CodeIsValid(string code)
{
return code == "dbddhkp";
}
}
I try to call that Action from within an Angular Component:
this._http.post<any>(http://localhost:29438/upload/codeisvalid', { code: 'wrongcode'}).subscribe(data => {
this.codeIsValid=data;
this.codeChecked=true;
});
The action is called, but "code" is always null. I also tried to modify the Action to public bool CodeIsValid([FromBody] string code)
(adding "[FromBody]") but then the method is not called anymore, but receive an error 400 instead
"The JSON value could not be converted to System.String"
What Do I have to change to make this work?
CodePudding user response:
Assuming all else works, instead of passing an object, just pass in 'wrongcode'
. C# is expecting only a string to be passed in, not a property of an object.
this._http.post<any>('http://localhost:29438/upload/codeisvalid', 'wrongcode').subscribe(data => {
this.codeIsValid=data;
this.codeChecked=true;
});
CodePudding user response:
try to select another content type
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
this._http.post<any>(http://localhost:29438/upload/codeisvalid', { code: 'wrongcode'}, options). .....