代码之家  ›  专栏  ›  技术社区  ›  TomSelleck

参数字典包含空值,请求正文中存在参数

  •  0
  • TomSelleck  · 技术社区  · 8 年前

    我正在努力 POST 我的WebAPI的枚举。请求正文包含我的参数,控制器具有 [FromBody] 标签问题是,即使参数在主体中,我也会得到一个空条目错误。

    我有以下api控制器方法:

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

    哪里 Direction 在文件的枚举中 turtle.cs :

    {
        public enum Direction { N, S, E, W }
    
        public class Turtle
        {
           ...
        }
    }
    

    我想用以下方法 发布 从角度到webapi控制器的方向:

    html

    <button (click)="takeMove(0)">Up</button>
    

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

    enter image description here

    编辑 尝试使用字符串而不是int,运气不好:

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  1
  •   R. Richards    8 年前

    在这种情况下,您实际上只想将值发送回API,而不是对象。

    原因是,API将尝试查找名为 d Direction 尝试绑定时的枚举值是请求正文中的get。如果找不到要查找的内容,则只返回null。

    因为您只是传递一个枚举值,所以只需要将该值作为请求体包含。然后绑定将按预期工作。

    因此,与其将此作为帖子:

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

    您有:

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