Angular / ASP.NET Core 2.1 CORS 问题
Posted
技术标签:
【中文标题】Angular / ASP.NET Core 2.1 CORS 问题【英文标题】:Angular / ASP.NET Core 2.1 CORS issue 【发布时间】:2019-08-29 17:21:24 【问题描述】:情况是我有一个现有的 Angular 应用程序,我正在将后端服务更改为 ASP.NET Core 2.1。我已成功创建 API 并在 startup.cs 文件中的服务注册中启用了 CORS,但是当我尝试访问我的 api 的任何特定 url 时,出现此错误消息
访问 XMLHttpRequest 在 'https://localhost:44329/api/ThinkTank/Index' 来自原点 'http://localhost:4200' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源
我认为是我的启动页面有问题,所以我把它放在下面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CPDEPCoreApi
public class Startup
public Startup(IConfiguration configuration)
Configuration = configuration;
readonly string MyAllowSpecificOrigins = "https://localhost:44329";
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.AddCors(options =>
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
builder.WithOrigins("https://localhost:44329")
.AllowAnyHeader()
.AllowAnyMethod(); ;
);
);
services.Configure<CookiePolicyOptions>(options =>
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
routes.MapRoute(
name: "default",
template: "controller=Home/action=Index/id?");
);
提前感谢您的帮助。
【问题讨论】:
【参考方案1】:您的来源是 localhost:4200
而不是 localhost:44329
(那是您的服务器)。
将此行 builder.WithOrigins("https://localhost:44329")
更改为 builder.WithOrigins("http://localhost:4200")
【讨论】:
@Geeksan 你现在的Startup.cs
是什么?以上是关于Angular / ASP.NET Core 2.1 CORS 问题的主要内容,如果未能解决你的问题,请参考以下文章
Angular 和 Asp.Net Core - 启用 2 因素身份验证
Angular / ASP.NET Core 2.1 CORS 问题
ASP.NET Core Angular 2 Webpack 热模块替换
使用 Google Auth、Angular 4、ASP.Net Core 2 进行身份验证时出现 405