当前位置: 首页 > news >正文

白骑士的C#教学实战项目篇 4.3 Web开发

系列目录

上一篇:白骑士的C#教学实战项目篇 4.2 图形用户界面(GUI)应用

        在这一部分,我们将从桌面应用程序扩展到 Web 开发。Web 开发是现代软件开发的重要领域,涵盖了从前端用户界面到后端服务器逻辑的完整堆栈。在这部分中,我们将介绍 ASP.NET Core 的基础知识,学习如何创建和配置 Web API,并通过一个开发博客系统的项目来综合应用这些知识。

        Web 开发涉及到创建能够在浏览器中运行的应用程序。ASP.NET Core 是一个用于构建现代、云优先的 Web 应用程序的开源框架。它具有高性能、跨平台的特点,适用于开发各种类型的 Web 应用程序和服务。

ASP.NET Core基础

        ASP.NET Core 是一个轻量级、跨平台的框架,用于构建现代 Web 应用程序。它由模块化的中间件组件组成,允许开发人员根据需要配置和扩展应用程序。

创建一个简单的 ASP.NET Core 应用程序

  1. 安装 .NET SDK:确保已安装最新版本的 .NET SDK。可以从 Microsoft 官方网站下载。
  2. 创建新项目:在命令行中运行以下命令创建一个新的 ASP.NET Core Web 应用程序:
    dotnet new webapp -o MyWebApp
    cd MyWebApp
  3. 运行应用程序:
    dotnet run

        在浏览器中访问 ‘http://localhost:5000‘,可以看到一个简单的 ASP.NET Core Web 应用程序。

创建与配置Web API

        Web API 是用于构建 RESTful 服务的接口,允许不同的客户端(例如浏览器和移动设备)与服务器进行通信。ASP.NET Core 提供了简便的方式来创建和配置 Web API。

创建一个简单的 Web API

  1. 创建新项目:在命令行中运行以下命令创建一个新的 ASP.NET Core Web API 项目:
    dotnet new webapi -o MyWebAPI
    cd MyWebAPI

  2. 定义数据模型:在 ‘Models‘ 文件夹中创建一个新的数据模型,例如 ‘Post‘:
  3. 创建控制器:
    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();}
    }
  4. 运行应用程序:
    dotnet run

        在浏览器中访问 ‘http://localhost:5000/api/posts‘,可以看到一个简单的 Web API 服务。

实践项目:开发一个博客系统

        现在我们将综合运用 ASP.NET Core 技术,开发一个简单的博客系统。这个博客系统将包括基本的博客文章管理功能,如创建、读取、更新和删除(CRUD)。

项目结构

  1. 创建 ASP.NET Core 项目:
    dotnet new webapi -o BlogSystem
    cd BlogSystem
  2. 定义数据模型:在 ‘Models‘ 文件夹中创建数据模型 ‘BlogPost‘:
    public class BlogPost
    {public int Id { get; set; }public string Title { get; set; }public string Content { get; set; }public DateTime CreatedAt { get; set; }
    }
  3. 创建数据上下文:在 ‘Data‘ 文件夹中创建数据上下文 ‘BlogContext‘:
    using Microsoft.EntityFrameworkCore;public class BlogContext : DbContext
    {public BlogContext(DbContextOptions<BlogContext> options) : base(options) { }public DbSet<BlogPost> BlogPosts { get; set; }
    }
  4. 配置数据库连接:在 ‘appsettings.json‘ 文件中配置数据库连接字符串:
    "ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogDB;Trusted_Connection=True;MultipleActiveResultSets=true"
    }

  5. 配置启动文件:在 ‘Startup.cs‘ 文件中配置服务:
    public void ConfigureServices(IServiceCollection services)
    {services.AddDbContext<BlogContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));services.AddControllers();
    }

  6. 创建控制器:在 ‘Controllers‘ 文件夹中创建 ‘BlogPostsController‘:
    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);}
    }

  7. 运行应用程序:
    dotnet run

        在浏览器中访问 ‘http://localhost:5000/api/blogposts‘,可以看到一个简单的博客系统 API。

总结

        在本节中,我们从桌面应用程序扩展到 Web 开发,学习了 ASP.NET Core 的基础知识和如何创建和配置 Web API。通过开发一个博客系统的项目,我们综合运用了这些知识,展示了如何设计和实现一个实际的 Web 应用程序。继续练习和扩展这些项目,可以帮助您进一步提高 Web 开发技能,为更复杂的项目打下坚实的基础。

下一篇:白骑士的C#教学实战项目篇 4.4 游戏开发​​​​​​​

http://www.lryc.cn/news/427868.html

相关文章:

  • 【数据分析】(交互) 延迟互信息(熵、概率密度、高斯核、带宽估计)
  • html转vue项目
  • .NET系列 定时器
  • 【Golang】火焰图空白部分是什么?
  • Web框架 --- 解析Web请求 [FromBody] [FromQuery] [FromRoute] [FromHeader]
  • Messari 摘要报告:Covalent Network(CXT)2024 Q2 品牌重塑、AI模块化数据、亚太地区扩展、代币回购计划和网络增长
  • Open3D 计算点云的面状指数
  • python下麦克风设备选择和录音
  • 云和集群有什么区别?
  • 无人机视角下的EasyCVR视频汇聚管理:构建全方位、智能化的AI视频监控网络
  • 数字影像技术是如何改变我们看待世界的方式呢?
  • Chainlit实现启动页面选择不同的LLM启动器等设置界面
  • SQL - 增、改、删
  • 怎么屏蔽电脑监控软件?企业管理者的智慧选择——精准定位,合理屏蔽,让监控软件成为助力而非障碍!
  • Linux·权限与工具-make
  • C++的序列容器——数组
  • TCC 和 XA 协议之间的区别?
  • 萌啦数据插件使用情况分析,萌啦数据插件下载
  • C++初学(13)
  • 目标检测之数据增强
  • 本地下载安装WampServer结合内网穿透配置公网地址远程访问详细教程
  • 一篇文章理清Java持久化脉络(关于JDBC、JPA、Hibernate、Spring Data JPA)
  • 【数学分析笔记】第2章第1节实数系的连续性(1)
  • Speech Synthesis (LASC11062)
  • 拟合与插值|线性最小二乘拟合|非线性最小二乘拟合|一维插值|二维插值
  • 《python语言程序设计》2018版第7章第05题几何:正n边形,一个正n边形的边都有同样的长度。角度同样 设计RegularPolygon类
  • 使用Virtio Driver实现一个计算阶乘的小程序——QEMU平台
  • 【PyCharm】配置“清华镜像”地址
  • IO器件性能评估
  • 在js中判断对象是空对象的几种方法