【发布时间】:2020-01-02 04:38:48
【问题描述】:
我有一个带有 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)
【问题讨论】:
-
嘿,您是否尝试过使用代理重定向? angular.io/guide/build#proxying-to-a-backend-server
-
我没试过。但是,好吧,这必须有效。我不明白为什么它不起作用
-
很好的请求总是很难处理
-
告诉我它是否有效;)
标签: javascript c# angular .net-core