我在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)
我想你需要 AllowAnyOrigin
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
或通过原点
app.UseCors(x => x.WithOrigins('https://localhost:44323').AllowAnyMethod().AllowAnyHeader());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句