【发布时间】:2020-04-15 17:14:59
【问题描述】:
我在 MVC Core 中创建了一个 API 项目。在我的控制器中,我添加了一些与 Postman 完美配合的 GET 和 POST 方法的 API。但是当我尝试从我的 Angular 应用程序中调用它们时,它们给了我 CORS 错误:
CORS 策略已阻止从源访问 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头
我搜索了解决方案,发现我需要添加 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 Controller:
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();
}
}
}
【问题讨论】:
-
这个问题和角度标签有什么关系?
-
Angular 通常运行一个 web-pack 开发服务器,默认情况下在端口 4200 上运行,而您的服务器通常在不同的端口上运行,该端口只允许来自相同来源的请求,因此它正在运行的端口相同来自您的开发服务器的 http 请求是一个跨域请求,将被您的服务器阻止。要解决这个问题,您需要根据您使用的服务器允许来自服务器的跨域请求。但在 Express 中,您只需添加: const cors = require('cors'); app.use(cors({origin:"localhost:4200", credentials: true})) 安装cors包后
标签: angular api asp.net-core cors asp.net-core-mvc