I'm trying to POST
an enum to my WebAPI. The request body contains my parameter, and the controller has a [FromBody]
tag. The problem is that I'm getting a null entry error even though the parameter is in the body.
I have the following api controller method:
public ApiResponse Post([FromBody]Direction d)
{
...
}
Where Direction
is in an enum in a file turtle.cs
:
{
public enum Direction { N, S, E, W }
public class Turtle
{
...
}
}
I'm trying to use the following to POST
a direction to the webapi controller from Angular:
html
<button (click)="takeMove(0)">Up</button>
service.ts
takeMove (d: number): Observable<Object> {
return this.http.post<Object>(this.gameModelUrl, {'d': d}, { headers: this.headers })
.pipe(
tap(gameModel => console.log(`fetched gamedata`)),
catchError(this.handleError('getGameData', {}))
);
}
Request + Error in Chrome:
POST https://localhost:44332/api/tasks 400 ()
MessageDetail: "The parameters dictionary contains a null entry for parameter 'd' of non-nullable type 'TurtleChallenge.Models.Direction' for method 'Models.ApiResponse Post(TurtleChallenge.Models.Direction)' in 'TaskService.Controllers.TasksController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
Edit Tried using string instead of int, no luck:
In this situation, you really only want to send the value back to the API, and not an object.
The reason is, the API is going to try and find a property named d
in the Direction
enum when it tries to bind the value is gets in the request body. If it doesn't find what it is looking for, it just returns null.
Since you are just passing an enum value, you just need to include that values as the request body. Then the binding will work as expected.
So, rather than this as the post:
this.http.post<Object>(this.gameModelUrl, {'d': d}, { headers: this.headers })...
You have this:
this.http.post<Object>(this.gameModelUrl, d, { headers: this.headers })...