跨域资源共享策略阻止了对XMLHttpRequest的访问:所请求的资源没有'Access-Control-Allow-Origin'头部。

3
我在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`文件代码:
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();
        }
    }
}


这个问题与Angular标签有什么关系? - Selaka Nanayakkara
Angular通常运行在端口4200上的web-pack dev-server,而您的服务器通常运行在不同的端口上,只允许来自相同来源的请求,因此从dev-server发出的http请求是跨域请求,会被服务器阻止。为了解决这个问题,您需要根据所使用的服务器允许跨域请求。但在Express中,您只需添加以下内容:const cors = require('cors'); app.use(cors({origin:"http://localhost:4200", credentials: true})) 在安装cors包之后即可。 - yaxx
2个回答

7
你需要在你的Web Api中启用CORS。 全局启用CORS的更简单和首选方法是将以下内容添加到web.config文件中。
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

更新:

在ASP.Net Core中,我们不再使用web.config文件,而是使用app.config文件。但您仍然需要拥有web.config文件,可以添加一个Web配置项模板。您可以使用它来更改最大文件上传限制等内容。

当您发布项目时,将生成web.config文件。


1
我从 Startup.cs 中删除了CORS代码。只需在web.config中添加这些设置即可。 - Tahreem Iqbal

1
在 .Net 5 中,我们可以通过在 startup.cs 中启用以下默认策略来实现此目的。
  services.AddCors(options =>
    {
        options.AddDefaultPolicy(
            builder =>
            {
                builder.WithOrigins("http://example.com",
                                    "http://www.contoso.com");
            });
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接