'Access-Control-Allow-Origin' ASP.NET 酷睿6



Postman中进行了测试,运行良好。在浏览器中我得到这个错误:

访问XMLHttpRequest'http://localhost:5081/api/Accounting/GetSales'来自原点'https://localhost:44426'已被CORS策略阻止:否请求的上存在"Access Control Allow Origin"标头资源

使用Angular和.Net6 的Asp-Net核心项目

[DisableCors]
[HttpGet("GetSales")]
public IEnumerable<SaleDto> GetSales()
{
var result = _context.Sales.Select(x => new SaleDto
{
AccountName = x.Account.Name,
CategoryName = x.Category.CategoryName,
SaleDate = x.SaleDate,
SaleId = x.SaleId,
SaleValue = x.SaleValue,
});
return result;
}

在注册中间件时,您有正确的条目吗?在ASP.NET Core中启用跨源请求(CORS(。

您需要添加localhost和端口号。我相信端口号目前是造成问题的原因。如果两个站点的端口号相同,则可能不会出现此问题。另外,请参阅同一域上CORS错误的答案。同一域上的CORS错误?

此外,您希望启用CORS而不是禁用它。CORS放宽了安全措施,这样您的代码就可以跨端口访问。

对我有用的是放置

app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
);

之前

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

在您的Program.csstartup.cs

然后你可以更改你的配置

在Appsetting.json文件中{"AllowOrigins":"https://localhost:4200"}

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

var allowOrigins = Configuration.GetValue<string>("AllowOrigins");
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins(allowOrigins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
options.AddPolicy("AllowHeaders", builder =>
{
builder.WithOrigins(allowOrigins)
.WithHeaders(HeaderNames.ContentType, HeaderNames.Server, HeaderNames.AccessControlAllowHeaders, HeaderNames.AccessControlExposeHeaders, "x-custom-header", "x-path", "x-record-in-use", HeaderNames.ContentDisposition);
});
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "DatingApp", Version = "v1" });
});
//authentication

                                                                                                                                                                      
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ExceptionMiddleware>();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DatingApp v1"));
//if (env.IsDevelopment())
//{
//    app.UseDeveloperExceptionPage();
//    }
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
//authentication
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

}

我遇到了类似的问题,我尝试将前端部分的头从我进行调用的地方更改,然后直接更改到控制器,但对我有效的是更改API项目的Start.cs文件并添加以下内容。我建议先在本地主机中尝试,然后在实际拥有API的地方部署更改。

public class Startup
{
private readonly string _MyCors = "MyCors";
.
.
.
public void ConfigureServices(...)
{
.
.
.
//Under your services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: _MyCors, builder =>
{
//for when you're running on localhost
builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") 
.AllowAnyHeader().AllowAnyMethod();

//builder.WithOrigins("url from where you're trying to do the requests")
});
});
}
public void Configure(.....)
{
//before the app.UseAuthorization & app.UseEndpoints
app.UseCors(_MyCors);
}
}

另一件需要检查的事情是确保您的原点拼写正确。

我有";http://localhost:4200/"不知何故;http://localhost:4200"。

花了很多小时才弄清楚。

最新更新