gpt4 book ai didi

asp.net-core - 在 ASP.Net Core 5 WebAPI 中启用 CORS

转载 作者:行者123 更新时间:2023-12-05 02:46:20 26 4
gpt4 key购买 nike

与此问题相关的文章和问题数以百万计,但我找不到我的代码有什么问题。我有 StartupStartupProductionStartupDevelopment,如下所示。此外,我正在使用 ASP.Net Core 5,并基于 documentation我认为我这样做是正确的。

仅供引用,起初,我使用 AllowAnyOrigin 进行开发,但我也测试了 .WithOrigins("http://localhost:3000") 并且它工作正常。我的后端在开发中在 https://localhost:44353 下运行,在生产中在 https://api.example.com 下运行。

public class Startup
{
protected const string CorsPolicyName = "CorsPolicyName";

public virtual void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(
new System.Text.Json.Serialization.JsonStringEnumConverter());
});

services.AddABunchOfOtherServices();
}

public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(CorsPolicyName);
app.UseAuthentication();
app.UseAuthorization();

app.UseMiddleware<CheckUserConfirmedMiddleware>();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute
(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
)
.RequireCors(CorsPolicyName);
});
}
}

public class StartupProduction : Startup
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(
CorsPolicyName,
policy => policy
.WithOrigins("https://example.com", "http://example.com")
//.WithOrigins(Configuration.GetValue<string>("AllowedHosts").Split(';').ToArray())
.AllowAnyMethod()
.AllowAnyHeader());
});

base.ConfigureServices(services);
}

public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware(typeof(ErrorHandlingMiddleware));

// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();

base.Configure(app, env);
}
}

public class StartupDevelopment : Startup
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
options.AddPolicy(
CorsPolicyName,
policy =>
policy
//.AllowAnyOrigin()
.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
)
);

base.ConfigureServices(services);

services.AddSwaggerGen(....);
}

public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<DevelopmentErrorHandlingMiddleware>();

base.Configure(app, env);

app.UseSwagger();

app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("swagger/v1/swagger.json", "API v1");
options.RoutePrefix = string.Empty;
});
}
}

我也尝试了 default policy .

更新

我已经在 visual studio 中将 Environment 设置为 Production 进行调试,现在我在开发中遇到了同样的问题。

Access to fetch at 'https://localhost:44353/api/v1/User' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决方案

我注意到是 IIS 阻止了请求。它仅在我的 appsettings.json 中有 "AllowedHosts": "*", 时才有效。因此,作为一种解决方法,我在我的 appsettings.json 中添加了 "MyRandomKey": "https://example.com", 并在我的 中使用了以下内容>启动

services.AddCors(options =>
options.AddPolicy(
CorsPolicyName,
policy =>
policy
.WithOrigins(Configuration.GetValue<string>("MyRandomKey").Split(";").ToArray())
.AllowAnyMethod()
.AllowAnyHeader()
)
);

最佳答案

AllowedHosts 和 CORS 不同。

AllowedHosts 用于主机过滤,因此即使您在应用程序中配置了 CORS 策略但不允许主机,IIS 也会拒绝该请求。

请引用此链接: Difference between AllowedHosts in appsettings.json and UseCors in .NET Core API 3.x

默认情况下它是 * 但您可以根据您的要求将其更改为。在您的情况下,您可以设置“api.example.com”,或者如果您还想允许来自本地主机,则设置“api.example.com;localhost”。设置完成后,IIS 将开始接受来自这些域的请求。

一旦 IIS 开始接受请求,您的应用程序级别配置的 CORS 策略将被应用和工作。所以基本上 CORS 是允许访问您的 WebAPI 中的资源。

关于asp.net-core - 在 ASP.Net Core 5 WebAPI 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65546175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com