赞
踩
上一篇:白骑士的C#教学实战项目篇 4.2 图形用户界面(GUI)应用
在这一部分,我们将从桌面应用程序扩展到 Web 开发。Web 开发是现代软件开发的重要领域,涵盖了从前端用户界面到后端服务器逻辑的完整堆栈。在这部分中,我们将介绍 ASP.NET Core 的基础知识,学习如何创建和配置 Web API,并通过一个开发博客系统的项目来综合应用这些知识。
Web 开发涉及到创建能够在浏览器中运行的应用程序。ASP.NET Core 是一个用于构建现代、云优先的 Web 应用程序的开源框架。它具有高性能、跨平台的特点,适用于开发各种类型的 Web 应用程序和服务。
ASP.NET Core 是一个轻量级、跨平台的框架,用于构建现代 Web 应用程序。它由模块化的中间件组件组成,允许开发人员根据需要配置和扩展应用程序。
- dotnet new webapp -o MyWebApp
- cd MyWebApp
dotnet run
在浏览器中访问 ‘http://localhost:5000‘,可以看到一个简单的 ASP.NET Core Web 应用程序。
Web API 是用于构建 RESTful 服务的接口,允许不同的客户端(例如浏览器和移动设备)与服务器进行通信。ASP.NET Core 提供了简便的方式来创建和配置 Web API。
- dotnet new webapi -o MyWebAPI
- cd MyWebAPI
- public class Post
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public string Content { get; set; }
- }
在 ‘Controllers‘ 文件夹中创建一个新的控制器,例如 ‘PostsController‘:
- using Microsoft.AspNetCore.Mvc;
- using System.Collections.Generic;
- using System.Linq;
-
-
- [Route("api/[controller]")]
-
- [ApiController]
- public class PostsController : ControllerBase
- {
- private static List<Post> posts = new List<Post>
- {
- new Post { Id = 1, Title = "First Post", Content = "This is the first post" },
- new Post { Id = 2, Title = "Second Post", Content = "This is the second post" }
- };
-
- [HttpGet]
- public ActionResult<IEnumerable<Post>> GetPosts()
- {
- return posts;
- }
-
- [HttpGet("{id}")]
- public ActionResult<Post> GetPost(int id)
- {
- var post = posts.FirstOrDefault(p => p.Id == id);
-
- if (post == null)
- {
- return NotFound();
- }
- return post;
- }
-
- [HttpPost]
- public ActionResult<Post> CreatePost(Post post)
- {
- post.Id = posts.Max(p => p.Id) + 1;
- posts.Add(post);
- return CreatedAtAction(nameof(GetPost), new { id = post.Id }, post);
- }
-
- [HttpPut("{id}")]
- public IActionResult UpdatePost(int id, Post post)
- {
- var existingPost = posts.FirstOrDefault(p => p.Id == id);
-
- if (existingPost == null)
- {
- return NotFound();
- }
- existingPost.Title = post.Title;
- existingPost.Content = post.Content;
- return NoContent();
- }
-
- [HttpDelete("{id}")]
- public IActionResult DeletePost(int id)
- {
- var post = posts.FirstOrDefault(p => p.Id == id);
-
- if (post == null)
- {
- return NotFound();
- }
- posts.Remove(post);
- return NoContent();
- }
- }

dotnet run
在浏览器中访问 ‘http://localhost:5000/api/posts‘,可以看到一个简单的 Web API 服务。
现在我们将综合运用 ASP.NET Core 技术,开发一个简单的博客系统。这个博客系统将包括基本的博客文章管理功能,如创建、读取、更新和删除(CRUD)。
- dotnet new webapi -o BlogSystem
- cd BlogSystem
- public class BlogPost
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public string Content { get; set; }
- public DateTime CreatedAt { get; set; }
- }
- using Microsoft.EntityFrameworkCore;
-
-
- public class BlogContext : DbContext
- {
- public BlogContext(DbContextOptions<BlogContext> options) : base(options) { }
- public DbSet<BlogPost> BlogPosts { get; set; }
- }
- "ConnectionStrings": {
- "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogDB;Trusted_Connection=True;MultipleActiveResultSets=true"
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<BlogContext>(options =>
- options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
-
- services.AddControllers();
- }
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
-
- [Route("api/[controller]")]
-
- [ApiController]
- public class BlogPostsController : ControllerBase
- {
- private readonly BlogContext _context;
-
- public BlogPostsController(BlogContext context)
- {
- _context = context;
- }
-
- [HttpGet]
- public async Task<ActionResult<IEnumerable<BlogPost>>> GetBlogPosts()
- {
- return await _context.BlogPosts.ToListAsync();
- }
-
- [HttpGet("{id}")]
- public async Task<ActionResult<BlogPost>> GetBlogPost(int id)
- {
- var blogPost = await _context.BlogPosts.FindAsync(id);
-
- if (blogPost == null)
- {
- return NotFound();
- }
-
- return blogPost;
- }
-
- [HttpPost]
- public async Task<ActionResult<BlogPost>> CreateBlogPost(BlogPost blogPost)
- {
- _context.BlogPosts.Add(blogPost);
- await _context.SaveChangesAsync();
-
- return CreatedAtAction(nameof(GetBlogPost), new { id = blogPost.Id }, blogPost);
- }
-
- [HttpPut("{id}")]
- public async Task<IActionResult> UpdateBlogPost(int id, BlogPost blogPost)
- {
- if (id != blogPost.Id)
- {
- return BadRequest();
- }
-
- _context.Entry(blogPost).State = EntityState.Modified;
-
- try
- {
- await _context.SaveChangesAsync();
- }
-
- catch (DbUpdateConcurrencyException)
- {
- if (!BlogPostExists(id))
- {
- return NotFound();
- }
-
- else
- {
- throw;
- }
- }
-
- return NoContent();
- }
-
- [HttpDelete("{id}")]
- public async Task<IActionResult> DeleteBlogPost(int id)
- {
- var blogPost = await _context.BlogPosts.FindAsync(id);
-
- if (blogPost == null)
- {
- return NotFound();
- }
-
- _context.BlogPosts.Remove(blogPost);
- await _context.SaveChangesAsync();
-
- return NoContent();
- }
-
- private bool BlogPostExists(int id)
- {
- return _context.BlogPosts.Any(e => e.Id == id);
- }
- }

dotnet run
在浏览器中访问 ‘http://localhost:5000/api/blogposts‘,可以看到一个简单的博客系统 API。
在本节中,我们从桌面应用程序扩展到 Web 开发,学习了 ASP.NET Core 的基础知识和如何创建和配置 Web API。通过开发一个博客系统的项目,我们综合运用了这些知识,展示了如何设计和实现一个实际的 Web 应用程序。继续练习和扩展这些项目,可以帮助您进一步提高 Web 开发技能,为更复杂的项目打下坚实的基础。
下一篇:白骑士的C#教学实战项目篇 4.4 游戏开发
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。