![](/img/trans.png)
[英]c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]CORS in .NET Core 2.0 “No 'Access-Control-Allow-Origin' header is present on the requested resource.”
我使用Core 2.0創建了一個web api,並且在執行跨域調用時啟用了cors,接收到以下錯誤:“請求的資源上沒有'Access-Control-Allow-Origin'標頭。”
以下是我在startup.cs中的配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddMvc();
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
app.UseCors("AllowAll");
}
根據我在stackoverflow上看到的每個帖子/教程,或者在哪里,這是允許所有來源的正確方法。 我錯過了什么?
嘗試調用: app.UseCors("AllowAll");
在app.UseMvc();
之前app.UseMvc();
。
文檔說明如下:
要為整個應用程序啟用CORS,請使用UseCors擴展方法將CORS中間件添加到請求管道。 請注意,CORS中間件必須位於應用程序中要支持跨源請求的任何已定義端點之前 (例如, 在調用UseMvc之前 )。
我可能錯了,但本教程應該可以幫到你。
以下是startup.cs中的配置
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddDbContext<DataContext>(x => x.UseInMemoryDatabase("TestDb"));
services.AddMvc();
services.AddAutoMapper();
// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
// configure DI for application services
services.AddScoped<IUserService, UserService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseAuthentication();
app.UseMvc();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.