我在MVC Core中创建了一个API项目,在我的控制器中添加了一些GET和POST方法,这些方法在Postman中运行得非常好。但是当我尝试从我的Angular应用程序调用它们时,它们会给我CORS错误:
``` Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource ```
我在Google上搜索解决方案并发现我需要添加CORS NuGet包。我已经这样做了,但错误仍然存在。
以下是我的`Startup.cs`文件代码:
``` Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource ```
我在Google上搜索解决方案并发现我需要添加CORS NuGet包。我已经这样做了,但错误仍然存在。
以下是我的`Startup.cs`文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using webapp1.Model;
namespace webapp1
{
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)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddDbContext<TodoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// 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.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors(options =>
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
}
}
}
以下是我的 API 控制器
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using webapp1.Model;
namespace webapp1.Controllers
{
[ApiController]
[Route("[controller]")]
public class TodoController : ControllerBase
{
TodoContext _context;
public TodoController(TodoContext context)
{
_context = context;
}
[HttpGet]
public List<Todo> Get()
{
return _context.Todos.ToList();
}
}
}