欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > 在 .NET 5.0 运行 .NET 8.0 教程:使用 ASP.NET Core 创建 Web API

在 .NET 5.0 运行 .NET 8.0 教程:使用 ASP.NET Core 创建 Web API

2025/5/12 9:23:30 来源:https://blog.csdn.net/m0_66323401/article/details/144631857  浏览:    关键词:在 .NET 5.0 运行 .NET 8.0 教程:使用 ASP.NET Core 创建 Web API

前言

因为我本机安装的是vs2019,所以我在使用vs创建项目的时候,只能选择.NET 5.0,而无法选择.NET 8.0
在这里插入图片描述
在网上有看到说用vs2019使用.net 8.0 ,但是感觉不可靠,要用还是安装vs2022吧。
我因为不想要安装vs2022。
但是微软教程上的代码又是基于.NET 8.0,对于从未接触过.NET CORE 的人来说,我运行不起来代码。
可以问ChatGPT,我就是在结合CHATGPT成功跑起来的。

关键核心部分

  1. 添加NuGet 包,记得选择符合自己框架版本的包版本。如.net 5.0 就需要选择5.x的包版本

  2. 在这里插入图片描述

  3. 教程中注册数据库上下文,.net 5.0 的Program.cs 是没有找到可以填写相关内容的地方。硬要填写估计是运行不起来的。

  4. 这部分注册就需要写在 startup.cs 代码文件中

  5. 在这里插入图片描述

整个startup.cs的代码

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using TodoApi20241005.Models;namespace TodoApi20241005
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// First Called// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllers();//这里添加数据库的连接//在 ASP.NET Core 中,服务(如数据库上下文)必须向依赖关系注入 (DI) 容器进行注册。 该容器向控制器提供服务。//注册数据库上下文services.AddDbContext<TodoContext>(opt =>opt.UseInMemoryDatabase("TodoList"));services.AddSwaggerGen();services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new OpenApiInfo { Title = "TodoApi20241005", Version = "v1" });});}// Second Called// 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.UseSwagger();app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TodoApi20241005 v1"));}app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}
}
  1. 然后就大功告成了,整个教程就这部分无法与.NET 5.0 兼容。因为是在不同的类文件里了。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词