使用 ASP.NET Core 创建 Web API(基于Net.Core 3.1和Visual Studio 2019)

本文档详细介绍了如何在Visual Studio 2019中使用ASP.NET Core 3.1创建一个简单的Web API项目。首先,创建一个新项目并选择ASP.NET Core Web API模板。接着,添加TodoItem模型类和TodoContext数据库上下文,利用InMemory数据库。随后,构建TodoItemsController,实现CRUD操作。最后,通过Postman测试API的正确性。

使用 ASP.NET Core 创建 Web API

创建Web项目

打开Visual Studio 2019,点击创建新项目

在这里插入图片描述

选择ASP.NET Core Web API

在这里插入图片描述

输入项目名称,勾选将解决方案和项目房租同一目录中

在这里插入图片描述

选择目标框架为.NET Core 3.1,勾选配置HTTPS

在这里插入图片描述
生成的项目目录结构如下图所示

在这里插入图片描述

运行项目会在浏览器中跳转出如下内容

在这里插入图片描述

添加模型类

在项目根目录下新建Models文件夹

在这里插入图片描述

点击右键,选择添加,选择

将类命名为TodoItem

在这里插入图片描述

新建的TodoItem类如图所示

在这里插入图片描述

替换TodoItem为如下内容:

public class TodoItem
{
    public long Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }
}

在这里插入图片描述

添加数据库上下文

点击工具,选择NuGet包管理器,选择管理解决方案的NuGet程序包

在这里插入图片描述

搜索Microsoft.EntityFrameworkCore.InMemory

在这里插入图片描述

右键单击 Models 文件夹,然后选择“添加” > “类” 。 将类命名为 TodoContext,然后单击“添加”。

在这里插入图片描述

输入如下代码:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;

namespace TodoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(opt =>
               opt.UseInMemoryDatabase("TodoList"));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

在这里插入图片描述

注册数据库上下文

在 ASP.NET Core 中,服务(如数据库上下文)必须向依赖关系注入容器进行注册。 该容器向控制器提供服务。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore; // 导入依赖
using TodoApi.Models; // 导入依赖

namespace TodoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 将数据库上下文添加到 DI 容器。
            // 指定数据库上下文将使用内存中数据库。
            services.AddDbContext<TodoContext>(opt =>
               opt.UseInMemoryDatabase("TodoList"));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

构建控制器

右键Controller文件夹。

选择添加,选择控制器

在这里插入图片描述

选择其操作使用Entity Framework的API控制器

在这里插入图片描述

  • 在“模型类”中选择“TodoItem (TodoApi.Models)” 。
  • 在“数据上下文类”中选择“TodoContext (TodoApi.Models)” 。
  • 选择“添加”。

在这里插入图片描述

生成文件结构下图所示

在这里插入图片描述

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;

namespace TodoApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoItemsController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoItemsController(TodoContext context)
        {
            _context = context;
        }

        // GET: api/TodoItems
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            return await _context.TodoItems.ToListAsync();
        }

        // GET: api/TodoItems/5
        [HttpGet("{id}")]
        public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);

            if (todoItem == null)
            {
                return NotFound();
            }

            return todoItem;
        }

        // PUT: api/TodoItems/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTodoItem(long id, TodoItem todoItem)
        {
            if (id != todoItem.Id)
            {
                return BadRequest();
            }

            _context.Entry(todoItem).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TodoItemExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/TodoItems
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
        {
            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
        }

        // DELETE: api/TodoItems/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<TodoItem>> DeleteTodoItem(long id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);
            if (todoItem == null)
            {
                return NotFound();
            }

            _context.TodoItems.Remove(todoItem);
            await _context.SaveChangesAsync();

            return todoItem;
        }

        private bool TodoItemExists(long id)
        {
            return _context.TodoItems.Any(e => e.Id == id);
        }
    }
}

使用Postman进行测试

在这里插入图片描述

### 创建 ASP.NET Core Web API 项目的步骤 在 Visual Studio 2019创建 ASP.NET Core Web API 项目时,需要确保已经安装了相关的开发工具组件。如果尚未安装这些组件,可以通过 Visual Studio 安装程序进行选择性安装。 启动 Visual Studio 2019 并点击“创建项目”选项。在弹出的模板列表中,选择“ASP.NET Core Web API”模板,并点击“下一步”。设置项目名称、位置以及解决方案名称后,点击“下一步”。 在框架选择界面,可以选择目标框架版本,例如 .NET Core 3.1 或更高版本[^3]。确认选择后,点击“创建”,系统会自动生成一个基本的 Web API 项目结构,包括控制器、Startup.cs 文件等。 生成的默认项目包含一个示例控制器(ValuesController),可以作为构建实际功能的基础。通过修改该控制器或添加新的控制器来实现特定业务逻辑。 ```csharp // 示例代码:创建一个简单的 ASP.NET Core Web API 控制器 using Microsoft.AspNetCore.Mvc; namespace MyWebApi.Controllers { [Route("[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } } ``` 为了测试 API 的功能,在调试模式下运行应用程序,Visual Studio 会自动打开浏览器并导航到指定的 API 路径,例如 `https://localhost:5001/api/values`,以查看返回的数据结果。 如果希望将项目部署到 IIS 上,则需确保已安装 Hosting Bundle,并且 IIS 模块支持 ASP.NET Core 应用程序。具体操作可参考官方文档或相关技术博客中的详细说明[^2]。 最后,对于初次使用 Visual Studio 2019 开发 ASP.NET Core 应用的开发者来说,可能需要注意某些版本兼容性问题,例如在安装过程中勾选“.NET SDK(Out of support)”选项后才能看到 ASP.NET Core 相关的项目模板[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值