从源对XMLHttpRequest的访问已被CORS策略阻止:请求的资源上不存在“ Access-Control-Allow-Origin”标头

时间:2019-12-24 17:29:56

标签: angular api asp.net-core cors asp.net-core-mvc

我已经在MVC Core中创建了一个API项目。在我的控制器中,我添加了一些GET和POST方法的API,这些API与Postman完美配合。但是,当我尝试从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();
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您需要在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核心中,我们没有web.config,而是有app.config文件。您仍然需要web.config才能添加Web配置项模板。您可以使用它来更改最大文件上传限制等。

发布项目时会生成web.config文件。