Can't get HTTP PUT request to work in ASP.NET Core

MyNameIsGuzse picture MyNameIsGuzse · Nov 11, 2018 · Viewed 11.5k times · Source

I'm trying to update an entry in the game table. However, my PUT request in ASP.NET never seems to trigger, and I can't figure out why.

This is controller in 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);
}

And this is the code I use in 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);
}

Edit 1: I do have a list of GET-requests, which all work just fine. It's only the PUT-request that fails.

Answer

Rahul picture Rahul · Nov 11, 2018

If you are using PUT request you need to add a resource id either to update or create new - so just don't combine your id with your object

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

If you are using Asp.net Core you can just re-write your URL on your HTTP verbs attribute like the code above - So pass your resource id in the URL and bind your object in the body - Your URL should read as https://localhost:44359/api/v1/game/2

Hope this helps you - Happy coding !!