設計RESTful API的C#接口時,需要遵循一些關鍵原則和最佳實踐。以下是一個基本的步驟指南,幫助你設計和實現一個RESTful API:
/users
、/products
、/orders
。以下是一個簡單的示例,展示如何使用ASP.NET Core Web API創建一個RESTful API:
MyApiProject/
├── Controllers/
│ └── UsersController.cs
├── Models/
│ └── User.cs
├── Services/
│ └── IUserService.cs
│ └── UserService.cs
├── Startup.cs
└── Program.cs
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public interface IUserService
{
Task<User> GetUserByIdAsync(int id);
Task<User> CreateUserAsync(User user);
Task<User> UpdateUserAsync(User user);
Task DeleteUserAsync(int id);
}
public class UserService : IUserService
{
private readonly List<User> _users = new List<User>
{
new User { Id = 1, Name = "John Doe", Email = "john@example.com" },
new User { Id = 2, Name = "Jane Doe", Email = "jane@example.com" }
};
public async Task<User> GetUserByIdAsync(int id)
{
return _users.FirstOrDefault(u => u.Id == id);
}
public async Task<User> CreateUserAsync(User user)
{
user.Id = _users.Max(u => u.Id) + 1;
_users.Add(user);
return user;
}
public async Task<User> UpdateUserAsync(User user)
{
var existingUser = _users.FirstOrDefault(u => u.Id == user.Id);
if (existingUser != null)
{
existingUser.Name = user.Name;
existingUser.Email = user.Email;
}
return existingUser;
}
public async Task DeleteUserAsync(int id)
{
var user = _users.FirstOrDefault(u => u.Id == id);
if (user != null)
{
_users.Remove(user);
}
}
}
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUser(int id)
{
var user = await _userService.GetUserByIdAsync(id);
if (user == null)
{
return NotFound();
}
return user;
}
[HttpPost]
public async Task<ActionResult<User>> CreateUser(User user)
{
var createdUser = await _userService.CreateUserAsync(user);
return CreatedAtAction(nameof(GetUser), new { id = createdUser.Id }, createdUser);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, User user)
{
if (id != user.Id)
{
return BadRequest();
}
var updatedUser = await _userService.UpdateUserAsync(user);
if (updatedUser == null)
{
return NotFound();
}
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteUser(int id)
{
await _userService.DeleteUserAsync(id);
return NoContent();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IUserService, UserService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
這個示例展示了如何創建一個簡單的RESTful API,包括定義資源、URI、HTTP方法和控制器。你可以根據實際需求擴展和修改這個示例。