設(shè)計(jì)一個(gè)C# .NET Core Web API需要考慮多個(gè)方面,包括路由、控制器、模型、數(shù)據(jù)訪問、身份驗(yàn)證和授權(quán)等。以下是一個(gè)基本的步驟指南,幫助你設(shè)計(jì)一個(gè)簡(jiǎn)單的Web API。
首先,使用Visual Studio或命令行工具創(chuàng)建一個(gè)新的.NET Core Web API項(xiàng)目。
dotnet new webapi -n MyApiApp
cd MyApiApp
在Startup.cs
文件中配置路由。默認(rèn)情況下,Web API會(huì)提供一個(gè)默認(rèn)的路由來處理所有的請(qǐng)求。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
創(chuàng)建一個(gè)控制器來處理HTTP請(qǐng)求。例如,創(chuàng)建一個(gè)UsersController
。
dotnet new controller -n UsersController
在UsersController.cs
中添加基本的CRUD操作。
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
[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> PostUser(User user)
{
_users.Add(user);
return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
}
[HttpPut("{id}")]
public IActionResult PutUser(int id, User user)
{
if (id != user.Id)
{
return BadRequest();
}
var index = _users.IndexOf(user);
if (index < 0)
{
return NotFound();
}
_users[index] = user;
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();
}
}
定義一個(gè)User
類來表示用戶數(shù)據(jù)。
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
運(yùn)行你的Web API項(xiàng)目,并使用工具如Postman或curl來測(cè)試API端點(diǎn)。
dotnet run
使用Postman:
GET /api/users
- 獲取所有用戶GET /api/users/1
- 獲取ID為1的用戶POST /api/users
- 創(chuàng)建一個(gè)新用戶PUT /api/users/1
- 更新ID為1的用戶DELETE /api/users/1
- 刪除ID為1的用戶為了添加身份驗(yàn)證和授權(quán),你可以使用ASP.NET Core Identity或其他身份驗(yàn)證庫。以下是一個(gè)簡(jiǎn)單的示例,使用ASP.NET Core Identity。
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
在Startup.cs
中配置Identity。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddControllers();
}
創(chuàng)建ApplicationDbContext
和ApplicationUser
類。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
public class ApplicationUser : IdentityUser
{
}
在appsettings.json
中添加數(shù)據(jù)庫連接字符串。
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyApiAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
再次運(yùn)行你的Web API項(xiàng)目,并使用身份驗(yàn)證保護(hù)端點(diǎn)。
dotnet run
使用Postman:
GET /api/users
- 需要身份驗(yàn)證POST /api/users
- 需要身份驗(yàn)證以上是一個(gè)基本的C# .NET Core Web API設(shè)計(jì)示例。你可以根據(jù)需要擴(kuò)展和修改這個(gè)示例,添加更多的功能,如數(shù)據(jù)驗(yàn)證、錯(cuò)誤處理、日志記錄等。