在 Asp Core 项目中启用 CORS 的问题
Posted
技术标签:
【中文标题】在 Asp Core 项目中启用 CORS 的问题【英文标题】:Problems Enabling CORS in Aps Core project 【发布时间】:2017-01-03 09:13:35 【问题描述】:大家!
我正在努力在 Asp.Core 项目中配置 CORS。
这是我的 Startup.cs 文件:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
namespace Api
public class Startup
public void ConfigureServices(IServiceCollection services)
services.AddMvcCore()
.AddJsonFormatters()
.AddAuthorization();
services.AddCors(options =>
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:54540").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
);
services.Configure<MvcOptions>(options =>
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
);
public void Configure(IApplicationBuilder app)
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
Authority = "http://localhost:54540",
RequireHttpsMetadata = false,
ScopeName = "api1",
AutomaticAuthenticate = true
);
app.UseMvc();
app.UseCors("AllowSpecificOrigin");
这是我的要求:
$.ajax(
type: "GET",
url: "http://localhost:1773/Claims/",
headers:
Authorization: "Bearer " + getUrlParameter("access_token"),
,
xhrFields:
withCredentials: true
).done(function (data)
alert(data);
);
我收到了这样的回复:
XMLHttpRequest cannot load http://localhost:1773/Claims/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54540' is therefore not allowed access. The response had HTTP status code 500.
我在控制器中添加了 [EnableCors("AllowSpecificOrigin")]。
如果有人可以帮助我,我将非常感激。
【问题讨论】:
***.com/questions/31942037/… 【参考方案1】:如果您在 CORS 中间件之前添加 MVC/IdentityServer 中间件,它将不起作用,因为 IdentityServer 中间件(假设 /Claims 由它处理)将处理请求并且不会调用后面的 MVC 和 CORS 中间件。
【讨论】:
以上是关于在 Asp Core 项目中启用 CORS 的问题的主要内容,如果未能解决你的问题,请参考以下文章
无法在 ASP.Net Core Web api 中启用 CORS
在 asp net core web api v3.0 中启用 CORS 的问题