在 .NET 5.0 运行 .NET 8.0 教程:利用 ASP.NET Core 创建 Web API
前言因为我本机安装的是vs2019,所以我在利用vs创建项目标时间,只能选择.NET 5.0,而无法选择.NET 8.0
https://i-blog.csdnimg.cn/direct/55e3171103c045c9a475ed3feb48a29a.png
在网上有看到说用vs2019利用.net 8.0 ,但是感觉不可靠,要用照旧安装vs2022吧。
我因为不想要安装vs2022。
但是微软教程上的代码又是基于.NET 8.0,对于从未接触过.NET CORE 的人来说,我运行不起来代码。
可以问ChatGPT,我就是在结合CHATGPT乐成跑起来的。
关键核心部门
[*] 添加NuGet 包,记得选择符合自己框架版本的包版本。如.net 5.0 就需要选择5.x的包版本
[*] https://i-blog.csdnimg.cn/direct/b1ac31ce3c7244a4a386cf9a4eb31416.png
[*] 教程中注册数据库上下文,.net 5.0 的Program.cs 是没有找到可以填写相关内容的地方。硬要填写估计是运行不起来的。
[*] 这部门注册就需要写在 startup.cs 代码文件中
[*] https://i-blog.csdnimg.cn/direct/c323d294cd6d4a6584ebf6f90a1b20a1.png
整个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();
});
}
}
}
[*]然后就大功告成了,整个教程就这部门无法与.NET 5.0 兼容。因为是在差别的类文件里了。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]