实战案例一:ASP.NET Core创建简单的RESTful API
在开始之前,你需要安装.NET Core SDK,这是一个跨平台的开发框架,可以用于创建Web应用程序、桌面应用程序、移动应用程序等。
- 创建项目:打开命令行工具,执行以下命令创建一个名为
MyApi的新项目。
dotnet new webapi -n MyApi
- 编写API逻辑:在
Controllers文件夹下创建一个名为ValuesController.cs的控制器,并编写以下代码。
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace MyApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private static readonly string[] Values = new string[] { "value1", "value2", "value3" };
// 获取所有值
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return Values;
}
// 根据ID获取值
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
if (id < 0 || id >= Values.Length)
{
return NotFound();
}
return Values[id];
}
// 添加新值
[HttpPost]
public void Post([FromBody] string value)
{
Values = Values.Append(value).ToArray();
}
// 更新值
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
if (id < 0 || id >= Values.Length)
{
return NotFound();
}
Values[id] = value;
}
// 删除值
[HttpDelete("{id}")]
public void Delete(int id)
{
if (id < 0 || id >= Values.Length)
{
return NotFound();
}
Values = Values.Where((v, i) => i != id).ToArray();
}
}
}
- 运行应用程序:在命令行中执行以下命令启动应用程序。
dotnet run
- 测试API:使用Postman或其他API测试工具访问
http://localhost:5000/api/values。
实战案例二:ASP.NET Core实现简单的身份验证
- 添加身份验证:在
Startup.cs文件中,将以下代码添加到ConfigureServices方法中。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
// ...
}
- 创建登录页面:在
Views/Account文件夹下创建一个名为Login.cshtml的页面。
@{
ViewData["Title"] = "登录";
}
<h2>登录</h2>
<form asp-action="Login">
<div>
<label asp-for="UserName"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div>
<label asp-for="Password"></label>
<input asp-for="Password" type="password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">登录</button>
</form>
- 配置登录控制器:在
Controllers/AccountController.cs文件中,添加以下方法。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MyApplication.Controllers
{
[Authorize]
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// 进行用户验证逻辑
// ...
return RedirectToAction("Index", "Home");
}
return View(model);
}
}
}
实战案例三:使用Entity Framework Core实现数据访问
- 添加Entity Framework Core依赖:在
Startup.cs文件中,将以下代码添加到ConfigureServices方法中。
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
- 创建数据模型:在
Models文件夹下创建一个名为Person.cs的类。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MyApplication.Models
{
[Table("People")]
public class Person
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(100)]
public string Address { get; set; }
public ICollection<Person> Friends { get; set; }
}
}
- 添加数据访问层:在
DAL文件夹下创建一个名为PersonRepository.cs的类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyApplication.DAL
{
public class PersonRepository
{
private readonly MyDbContext _context;
public PersonRepository(MyDbContext context)
{
_context = context;
}
public async Task<Person> GetPersonByIdAsync(int id)
{
return await _context.People.FindAsync(id);
}
public async Task<List<Person>> GetPeopleAsync()
{
return await _context.People.ToListAsync();
}
}
}
- 使用数据访问层:在控制器或服务中注入
PersonRepository并使用它来访问数据。
using Microsoft.AspNetCore.Mvc;
using MyApplication.Models;
using MyApplication.DAL;
namespace MyApplication.Controllers
{
public class PeopleController : Controller
{
private readonly PersonRepository _personRepository;
public PeopleController(PersonRepository personRepository)
{
_personRepository = personRepository;
}
public IActionResult Index()
{
var people = _personRepository.GetPeopleAsync();
return View(people);
}
}
}
实战案例四:使用SignalR实现实时通信
- 添加SignalR依赖:在
Startup.cs文件中,将以下代码添加到ConfigureServices方法中。
services.AddSignalR();
- 创建Hub:在
Hub文件夹下创建一个名为ChatHub.cs的类。
using Microsoft.AspNetCore.SignalR;
namespace MyApplication.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}
}
- 配置路由:在
Startup.cs文件中,将以下代码添加到Configure方法中。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chat");
});
}
- 使用Hub:在前端页面,创建一个连接到SignalR Hub的WebSocket连接,并实现发送和接收消息的逻辑。
const connection = new signalR.HubConnectionBuilder().withUrl("/chat").build();
connection.start().then(() =>
{
console.log("Connection started!");
connection.on("ReceiveMessage", (message) =>
{
console.log("Message received: " + message);
});
document.getElementById("sendButton").addEventListener("click", () =>
{
const message = document.getElementById("messageInput").value;
connection.send("SendMessage", message).then(() =>
{
console.log("Message sent!");
}).catch(err =>
{
console.log("Error sending message: " + err);
});
});
});
实战案例五:使用Blazor实现单页应用程序
- 添加Blazor依赖:在
Startup.cs文件中,将以下代码添加到ConfigureServices方法中。
services.AddServerSideBlazor();
- 创建Blazor组件:在
wwwroot文件夹下创建一个名为Index.cshtml的页面,并添加以下代码。
@page "/"
<h1>欢迎来到Blazor!</h1>
<p>您可以通过访问以下链接来了解有关Blazor的信息:</p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/aspnet/coreblazor/intro?view=aspnetcore-5.0">Blazor概述</a></li>
<li><a href="https://docs.microsoft.com/en-us/aspnet/coreblazor/components/fundamentals?view=aspnetcore-5.0">Blazor组件基础知识</a></li>
</ul>
- 配置路由:在
Startup.cs文件中,将以下代码添加到Configure方法中。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub("/blazor");
});
}
- 访问Blazor应用程序:在浏览器中访问
http://localhost:5000/,然后点击左侧菜单中的“Blazor”链接。
通过以上五个实战案例,你将能够快速掌握ASP开源框架,并在实际项目中应用所学知识。祝你学习愉快!
