I have coded RestAPI with .NET . I am using Postman to test the API. It is giving me successful http request for GET and DELETE. But throwing error for PUT and POST request.
Below are the codes I am using to create RestAPI.
Code: Player.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UnityRestAPI.Contracts
{
[JsonObject, Serializable]
public class Player
{
public int Id { get; set; }
public string FullName { get; set; }
public float Score { get; set; }
}
}
Code: PlayersController.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using UnityRestAPI.Contracts;
namespace UnityRestAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PlayersController : Controller
{
private static List<Player> Players = new List<Player>()
{
new Player
{
Id = 1,
FullName = "Michael Jordan",
Score = 1000
},
new Player
{
Id = 2,
FullName = "Steve Jobs",
Score = 2000
},
new Player
{
Id = 3,
FullName = "Carton John",
Score = 3000
},
};
// GET api/players
[HttpGet]
public JsonResult Get()
{
return Json(Players);
}
// GET api/players/5
[HttpGet("{id}")]
public JsonResult Get(int id)
{
Player player = Players.Single(p => p.Id == id);
return Json(player);
}
// POST api/players
[HttpPost]
public JsonResult Post([FromBody]Player newPlayer)
{
Players.Add(newPlayer);
return Json(Players);
}
// PUT api/players/5
[HttpPut("{id}")]
public JsonResult Put(int id, [FromBody] float newScore)
{
Player player = Players.Single(p => p.Id == id);
player.Score = newScore;
return Json(player);
}
// DELETE api/players/5
[HttpDelete("{id}")]
public void Delete(int id)
{
Player player = Players.Single(p => p.Id == id);
Players.Remove(player);
}
}
}
RestAPI GET request in Postman: Successful request
Postman Error for POST request in Postman: Input not valid