在 .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 兼容。因为是在不同的类文件里了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值