您好,登錄后才能下訂單哦!
在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();
}
}
創(chuàng)建一個(gè)ASP.NET Core Web應(yīng)用程序項(xiàng)目,并將上述Controller添加到項(xiàng)目中。
運(yùn)行應(yīng)用程序并通過(guò)瀏覽器或API測(cè)試工具(如Postman)訪問(wèn)以下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模式。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。