首先这是我的代码 - 我的控制器:
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 DataBase.Data;
using DataBase.Data.Models;
namespace DataBase.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FoodDatabasesController : ControllerBase
{
private readonly FoodDbContext _context;
public FoodDatabasesController(FoodDbContext context)
{
_context = context;
}
// GET: api/FoodDatabases
[HttpGet]
public async Task<ActionResult<IEnumerable<FoodDatabase>>> GetFoodDatabases()
{
return await _context.FoodDatabases.ToListAsync();
}
// GET: api/FoodDatabases/5
[HttpGet("{id}")]
public async Task<ActionResult<FoodDatabase>> GetFoodDatabase(int id)
{
var foodDatabase = await _context.FoodDatabases.FindAsync(id);
if (foodDatabase == null)
{
return NotFound();
}
return foodDatabase;
}
// PUT: api/FoodDatabases/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutFoodDatabase(int id, FoodDatabase foodDatabase)
{
if (id != foodDatabase.Id)
{
return BadRequest();
}
_context.Entry(foodDatabase).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!FoodDatabaseExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/FoodDatabases
[HttpPost]
public async Task<ActionResult<FoodDatabase>> PostFoodDatabase(FoodDatabase foodDatabase)
{
_context.FoodDatabases.Add(foodDatabase);
await _context.SaveChangesAsync();
return CreatedAtAction("GetFoodDatabase", new { id = foodDatabase.Id }, foodDatabase);
}
// DELETE: api/FoodDatabases/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteFoodDatabase(int id)
{
var foodDatabase = await _context.FoodDatabases.FindAsync(id);
if (foodDatabase == null)
{
return NotFound();
}
_context.FoodDatabases.Remove(foodDatabase);
await _context.SaveChangesAsync();
return NoContent();
}
private bool FoodDatabaseExists(int id)
{
return _context.FoodDatabases.Any(e => e.Id == id);
}
}
}
这是我的数据库实体和
DbContext
:
public class FoodDatabase
{
[Key]
public int Id { get; set; }
[MaxLength(150), Column(TypeName = "nvarchar(150)")]
public string Food { get; set; } = "Food Name";
[MaxLength(150), Column(TypeName = "nvarchar(300)")]
public string Description { get; set; } = "Description";
}
public class FoodDbContext : DbContext
{
public FoodDbContext(DbContextOptions<FoodDbContext> options)
: base(options)
{
}
public DbSet<FoodDatabase> FoodDatabases { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Seed data
modelBuilder.Entity<FoodDatabase>().HasData(
new FoodDatabase
{
Id = 1,
Food = "Foodbread",
Description = "A delicious bread made for food lovers"
});
}
}
这是我的两次迁移:
using Microsoft.EntityFrameworkCore.Migrations;
namespace DataBase.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "FoodDatabases",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Food = table.Column<string>(type: "nvarchar(150)", maxLength: 150, nullable: false),
Description = table.Column<string>(type: "nvarchar(300)", maxLength: 150, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_FoodDatabases", x => x.Id);
});
// Seed data
migrationBuilder.InsertData(
table: "FoodDatabases",
columns: new[] { "Id", "Food", "Description" },
values: new object[] { 1, "Foodbread", "A delicious bread made for food lovers" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FoodDatabases");
}
}
}
// <auto-generated />
using DataBase.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace DataBase.Migrations
{
[DbContext(typeof(FoodDbContext))]
partial class FoodDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("DataBase.Data.Models.FoodDatabase", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(150)
.HasColumnType("nvarchar(300)");
b.Property<string>("Food")
.IsRequired()
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.HasKey("Id");
b.ToTable("FoodDatabases");
});
#pragma warning restore 612, 618
}
}
}
最后是
program.cs
以及带有连接字符串的应用程序设置:
using DataBase.Data;
using DataBase.Data.Models;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<FoodDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("CORSPolicy",
builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting(); // <- This is required for routing
app.UseCors("CORSPolicy"); // Apply CORS policy
app.UseAuthorization();
app.MapControllers();
app.Run();
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Database = WebApiReact,Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
}
}
我目前面临的问题是,当我在 Swagger 中打开解决方案,并且我想尝试 get、post 和 put 函数时,它们总是抛出相同的错误。我很困惑为什么会发生这种情况,并寻求一些关于可以改进它的指导。
这是当我尝试执行 put 函数时在 Swagger 中遇到的错误:
错误:响应状态为 500
响应正文
System.Globalization.CultureNotFoundException:全球化不变模式仅支持不变区域性。有关更多信息,请参阅 https://aka.ms/GlobalizationInvariantMode。 (参数“名称”)
en-us 是无效的区域性标识符。
在 System.Globalization.CultureInfo.GetCultureInfo(字符串名称)
在 Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 commandBatches、IRelationalConnection 连接、CancellationToken CancellationToken)1 retry, SqlConnectionOverrides overrides) at Microsoft.Data.SqlClient.SqlConnection.InternalOpenAsync(CancellationToken cancellationToken) --- End of stack trace from previous location --- at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable
在 Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable1 commandBatches、IRelationalConnection 连接、CancellationToken CancellationToken)1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable
在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList4 操作,Func`4 verifySucceeded,CancellationToken CancellationToken)1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func
在Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(布尔acceptAllChangesOnSuccess,CancellationToken取消令牌)
在Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(布尔acceptAllChangesOnSuccess,CancellationToken取消令牌)
在 C:\Users\huday\Documents\DataBase\DataBase\Controllers\FoodDatabasesController.cs 中的 DataBase.Controllers.FoodDatabasesController.PutFoodDatabase(Int32 id, FoodDatabase foodDatabase):第 59 行在 Microsoft.AspNetCore.Mvc.Infrastruct.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext、IActionResultTypeMapper 映射器、ObjectMethodExecutor 执行器、对象控制器、Object[] 参数)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker 调用程序,ValueTask`1 actionResultValueTask)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用程序、任务上一个任务、下一个状态、范围范围、对象状态、布尔值已完成)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed 上下文)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.Next(状态&下一个,范围&范围,对象&状态,布尔&isCompleted)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ControllerActionInvoker.InvokeInnerFilterAsync()
--- 先前位置的堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|20_0(ResourceInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 调用程序、任务任务、IDisposable 范围)
在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 调用程序、任务任务、IDisposable 范围)
在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文)
在 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
在 Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext,ISwaggerProvider swaggerProvider)
在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文)
在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext 上下文)
标题
Accept: */*
Host: localhost:7181
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Content-Type: application/json
Origin: https://localhost:7181
Referer: https://localhost:7181/swagger/index.html
TE: trailers
Content-Length: 60
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
将项目不变全球化设置更改为 false。默认情况下,Dotnet 使用不变区域性。如果您想在示例中使用特定的(en-us),您应该这样做;
添加您的 csproj 文件:
项目.csproj
<InvariantGlobalization>false</InvariantGlobalization>
或定义环境变量:
环境变量
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT : false
或将 env 添加到您的 docker 文件中:
DockerFile
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
您还可以检查 了解其他支持的文化字符串