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

20 篇文章 0 订阅

        在这一部分,我们将从桌面应用程序扩展到 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 开发技能,为更复杂的项目打下坚实的基础。

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白骑士所长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值