gpt4 book ai didi

javascript - 仍然出现错误,已被 CORS 策略阻止

转载 作者:行者123 更新时间:2023-12-02 22:11:12 25 4
gpt4 key购买 nike

我有一个使用 Angular 8 的 asp.net core 3 应用程序。所以在 Angular 中我有这个方法:

 getValues() {
this.http.get('https://localhost:44323/api/Values/').subscribe(response => {
this.values = response;
}, error => {
console.log(error);
});
}

我的 cs 文件如下所示:

 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)
{

string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(connectionString));

services.AddCors();

services.AddControllers();
}

// 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.UseHttpsRedirection();

app.UseRouting();

app.UseCors();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.UseCors(x => x.WithOrigins().AllowAnyMethod().AllowAnyHeader());

}
}

所以我正在做 UseCors 的事情。但我仍然收到此错误:

Access to XMLHttpRequest at 'https://localhost:44323/api/Values/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当然,我用谷歌搜索了这个错误。这就是我使用 UseCors 的原因。但这是他们推荐的。但我仍然收到此错误。

所以我被困住了。如果有人能告诉我我做错了什么,那就太好了。

谢谢

我现在是这样的:

[EnableCors("AllowOrigin")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{

private protected DataContext _dataContext;
public ValuesController( DataContext dataContext)
{
this._dataContext = dataContext;
}
// GET api/values
[HttpGet]
[EnableCors("AllowOrigin")]
public async Task <IActionResult> GetValues()
{
var values = await _dataContext.Values.ToListAsync();

return Ok(values);

}

// GET api/values/5
[HttpGet("{id}")]
public async Task <IActionResult> GetValue(int id)
{
var value = await _dataContext.Values.FirstOrDefaultAsync(x => x.Id == id);

return Ok(value);
}

// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}

还有这个:


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)
{

string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(connectionString));

services.AddCors();
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

services.AddControllers();
}

// 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.UseHttpsRedirection();

app.UseRouting();

//app.UseCors();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.UseCors(x => x.WithOrigins("https://localhost:44323").AllowAnyHeader().AllowAnyMethod().AllowCredentials());

}
}

但是我会得到这个错误:

An unhandled exception occurred while processing the request.
InvalidOperationException: Endpoint DatingApp.API.Controllers.ValuesController.GetValues (DatingApp.API) contains CORS metadata, but a middleware was not found that supports CORS.
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code.
Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingCorsMiddlewareException(Endpoint endpoint)

最佳答案

好吧,终于解决了!!

我不知道这一点。诀窍是我这样做了:


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

//app.UseCors();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

So between routing and Authorization.

还有那个对我的帖子投票的人,方式不太好。以你为耻!!

关于javascript - 仍然出现错误,已被 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554246/

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