有意义的标题
- 连接Azure SQL 数据库
- 添加swagger
- 新建数据库
- 编写API
- API连接更新
简单的前端搭建结束后,就到了后端搭建了
连接Azure SQL 数据库
解决方案 => 发布中
服务依赖项添加,这步不难,不放具体步骤了
成功是这样的
添加swagger
-
Nuget 程序包先安装Swashbuckle.AspNetCore
-
在Program.cs中添加Swagger服务:
在builder.Services.AddControllersWithViews();之后添加:
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
- 在HTTP请求管道中配置Swagger中间件:
在app.UseRouting();之后添加以下代码来使用Swagger和Swagger UI中间件:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
- 你的Program.cs现在应该看起来像这样:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add Swagger services
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// Use Swagger middleware
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
app.Run();
- 修改调试启动url
在launchSettings.json中
"yourProject": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "https://localhost:[your port1]/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
},
"applicationUrl": "https://localhost:[your port1];http://localhost:[your port2]"
},
之后调试project就会自动跳到swagger了
新建数据库
可以通过AZURE门户用VS打开,就不细讲了
编写API
浅写了一个API试试Swagger
API连接更新
之后调试的时候发现连不上,对几个文件进行调整
appsettings.json更新
"ConnectionStrings": {
"DefaultConnection": "[yourConnectionStrings]"
},
DbContext.cs
using Microsoft.EntityFrameworkCore;
namespace yourProject
{
public class AppDbContext : DbContext
{
public DbSet<Users> Users { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}
}
Program.cs 更新
...
// Add services to the container, including DbContext
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
...
之后就能完美访问Azure SQL 数据库了
完美!
如果有帮助到你,能点个赞嘛!!谢谢!!!