我创建了小型 Rest API 应用程序并尝试使用 Postman 对其进行测试,但一无所获。
这是以下代码:
-动物
namespace VeterinaryClinicShelter.Models;
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public double Weight { get; set; }
public string FurColor { get; set; }
}
-动物控制器
using Microsoft.AspNetCore.Mvc;
using VeterinaryClinicShelter.Models;
namespace VeterinaryClinicShelter.Controllers;
[ApiController]
[Route("[controller]")]
public class AnimalController : ControllerBase
{
private static readonly List<Animal> Animals =
[
new Animal { Id = 1, Name = "Buddy", Category = "Dog", Weight = 15.2, FurColor = "Brown" },
new Animal { Id = 2, Name = "Whiskers", Category = "Cat", Weight = 7.5, FurColor = "White" },
new Animal { Id = 3, Name = "Fluffy", Category = "Cat", Weight = 6.8, FurColor = "Gray" },
new Animal { Id = 4, Name = "Max", Category = "Dog", Weight = 20.5, FurColor = "Black" },
new Animal { Id = 5, Name = "Snowball", Category = "Rabbit", Weight = 3.2, FurColor = "White" }
];
[HttpGet]
public ActionResult<List<Animal>> GetAnimals()
{
return Animals;
}
[HttpGet("{id}")]
public ActionResult<Animal> GetAnimalById(int id)
{
var animal = Animals.FirstOrDefault(a => a.Id == id);
if (animal == null)
{
return NotFound();
}
return animal;
}
[HttpPost]
public ActionResult<Animal> AddAnimal(Animal animal)
{
if (Animals.Any(a => a.Id == animal.Id))
{
return Conflict("Animal with such ID already exists");
}
Animals.Add(animal);
return CreatedAtAction(nameof(GetAnimalById), new { id = animal.Id }, animal);
}
[HttpPut("{id:int}")]
public ActionResult<Animal> EditAnimal(int id, Animal newAnimal)
{
var index = Animals.FindIndex(animal => animal.Id == id);
if (index == -1) return NotFound();
Animals[index].Name = newAnimal.Name;
Animals[index].Category = newAnimal.Category;
Animals[index].Weight = newAnimal.Weight;
Animals[index].FurColor = newAnimal.FurColor;
return NoContent();
}
[HttpDelete("{id:int}")]
public ActionResult<Animal> DeleteAnimal(int id)
{
var deleteAnimal = Animals.FirstOrDefault(animal => animal.Id == id);
if (deleteAnimal == null) return NotFound();
Animals.Remove(deleteAnimal);
return NoContent();
}
}
邮差GET请求:
http://localhost:5039/Animal/2
我确定我使用的是正确的端口。
如果该信息有帮助: IDE:Rider,模板:ASP.NET Core Web 应用程序模板,类型:Blazor Web App,框架:net8.0
我询问了这个问题,没有给我任何有用的信息。
你尝试过吗
return Ok(animal)
?
或者您的请求端点可能应以
"https:\\"
开头,而不是 "http:\\"