簡體   English   中英

參數字典包含空值,參​​數存在於請求主體中

[英]Parameters dictionary contains null value, parameter present in request body

我想POST枚舉我的WebAPI。 請求主體包含我的參數,並且控制器具有[FromBody]標記。 問題是,即使參數在主體中,我也會收到空輸入錯誤。

我有以下api控制器方法:

public ApiResponse Post([FromBody]Direction d)
{
    ...
}

其中Direction在文件turtle.cs的枚舉中:

{
    public enum Direction { N, S, E, W }

    public class Turtle
    {
       ...
    }
}

我試圖使用以下方法來POST的方向從棱角分明的WebAPI控制器:

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', {}))
      );
  }

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."

在此處輸入圖片說明

編輯嘗試使用字符串代替int,沒有運氣:

在此處輸入圖片說明

在這種情況下,您實際上只想將值發送回API,而不是對象。

原因是,API試圖綁定在請求正文中獲取的值時,將嘗試在Direction枚舉中找到名為d的屬性。 如果找不到要查找的內容,則返回null。

由於您只是傳遞一個枚舉值,因此只需要將該值包含為請求正文即可。 然后綁定將按預期工作。

因此,與其將其作為帖子:

this.http.post<Object>(this.gameModelUrl, {'d': d}, { headers: this.headers })...

你有這個:

this.http.post<Object>(this.gameModelUrl, d, { headers: this.headers })...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM