【问题标题】:Can't get HTTP PUT request to work in ASP.NET Core无法让 HTTP PUT 请求在 ASP.NET Core 中工作
【发布时间】:2018-11-10 23:48:39
【问题描述】:

我正在尝试更新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);
}

这是我在 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);
}

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

【问题讨论】:

  • 您的其他 ASP.Net 控制器是否成功调用 Angular? Q:你试过用RouteDebugger吗?

标签: c# angular rest asp.net-core asp.net-core-routing


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    路由模板参数{update.GameID} 不符合文档建议的标准

    假设游戏id是整数,则如下查看

    //PUT .../game/5
    [Route("game/{id:int}")]
    [HttpPut]
    public IActionResult updateGame(int id, [FromBody]Game update) {
        //...
    }
    

    参考Routing to controller actions in ASP.NET Core

    我还建议您查看操作的逻辑,因为我认为它不会像您认为的那样更新从上下文返回的实体。

    【讨论】:

    • 是的。 result = update 并没有按照你的想法去做。
    • 我这样做了,但是当我尝试 put-request 时它仍然不会调用。我在updateGame() 上添加了一个断点,并尝试通过邮递员发出 put-request,但它从未触发。
    • 正如@Nkosi 建议的那样,它可能无法达到您的预期。另请查看docs.microsoft.com/en-us/aspnet/core/tutorials/…,有一个 PUT 示例。
    【解决方案3】:

    你能像修改你的定义路线一样

    [Route("game")]
    [HttpPut]
    public IActionResult updateGame([FromBody]Game update)
    {
       //your code
    }
    

    从角度调用

    putGame(game:Game){
        return this._http.put(this.url + "game", game);
    }
    

    你可以从游戏对象接收gameid,所以不需要从url

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 2021-02-15
      • 2014-10-20
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      相关资源
      最近更新 更多