【发布时间】: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?}");
});
}
}
}
提前感谢您的帮助。
【问题讨论】:
标签: c# angular asp.net-web-api asp.net-core cors