您好,登錄后才能下訂單哦!
在C#中模擬Spring的MVC模式,你可以使用ASP.NET Core Web API
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private static readonly List<User> _users = new List<User>
{
new User { Id = 1, Name = "Alice", Email = "alice@example.com" },
new User { Id = 2, Name = "Bob", Email = "bob@example.com" }
};
[HttpGet]
public ActionResult<IEnumerable<User>> GetUsers()
{
return Ok(_users);
}
[HttpGet("{id}")]
public ActionResult<User> GetUser(int id)
{
var user = _users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
[HttpPost]
public ActionResult<User> CreateUser(User user)
{
_users.Add(user);
return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
}
[HttpPut("{id}")]
public IActionResult UpdateUser(int id, User user)
{
var existingUser = _users.FirstOrDefault(u => u.Id == id);
if (existingUser == null)
{
return NotFound();
}
existingUser.Name = user.Name;
existingUser.Email = user.Email;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteUser(int id)
{
var user = _users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return NotFound();
}
_users.Remove(user);
return NoContent();
}
}
創建一個ASP.NET Core Web應用程序項目,并將上述Controller添加到項目中。
運行應用程序并通過瀏覽器或API測試工具(如Postman)訪問以下URL:
GET /api/users
GET /api/users/{id}
POST /api/users
PUT /api/users/{id}
DELETE /api/users/{id}
這樣,你就使用C#和ASP.NET Core Web API模擬了Spring MVC模式。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。