无法让 HTTP PUT 请求在 ASP.NET Core 中工作

MyN*_*zse 2 c# rest asp.net-core asp.net-core-routing angular

我正在尝试更新表中的条目game。但是,我在 ASP.NET 中的 PUT 请求似乎永远不会触发,我不知道为什么。

这是 ASP.NET 中的控制器:

[Route("game/{update.GameID}")]
[HttpPut]
public IActionResult updateGame([FromBody]Game update)
{
    var result = context.Games.SingleOrDefault(g => g.GameID == update.GameID);
    if (result != null)
    {
        result = update;
        context.SaveChanges();
    }
    return Created("", result);
}
Run Code Online (Sandbox Code Playgroud)

这是我在 Angular 中使用的代码:

url:string;
constructor(private _http: HttpClient) {
    this.url = "https://localhost:44359/api/v1/"
};

putGame(id:number, game:Game){
    return this._http.put(this.url + "game/" + id, game);
}
Run Code Online (Sandbox Code Playgroud)

编辑 1:我确实有一个 GET 请求列表,它们都可以正常工作。只有 PUT 请求失败了。

Rah*_*hul 6

如果您正在使用PUT请求,您需要添加一个资源 id 来更新或创建新的 - 所以不要将您的 id 与您的对象结合起来

[HttpPut("game/{id}")]
public IActionResult UpdateGame(int id, [FromBody]Game update) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Asp.net Core,您可以像上面的代码一样在 HTTP 动词属性上重写您的 URL - 所以在 URL 中传递您的资源 id 并在正文中绑定您的对象 - 您的 URL 应该读作https://localhost:44359/api/v1/game/2

希望这对您有所帮助 - 编码愉快!!