Blazor和Webapi Cors支持
我花了好几天的时间想弄明白这一点。我发现的所有例子都不起作用,或者我不理解一些东西。我有一个.netCore webapi当前正在运行https://localhost:5001,以及上的独立blazor Webassemblyhttps://localhost:5002. 我从blazor启动一个http请求:Blazor和Webapi Cors支持,cors,asp.net-core-webapi,blazor-webassembly,Cors,Asp.net Core Webapi,Blazor Webassembly,我花了好几天的时间想弄明白这一点。我发现的所有例子都不起作用,或者我不理解一些东西。我有一个.netCore webapi当前正在运行https://localhost:5001,以及上的独立blazor Webassemblyhttps://localhost:5002. 我从blazor启动一个http请求: protected async override void OnInitialized() { base.OnInitialized(); string reqUrl
protected async override void OnInitialized()
{
base.OnInitialized();
string reqUrl = $"https://localhost:5001/api/District/";
var response = await http.GetAsync(reqUrl);
}
在webapi上,我有以下startup.cs:
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();
// For Entity Framework
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
// For Identity
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Adding Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
// Adding Jwt Bearer
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT:ValidAudience"],
ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
};
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder.WithOrigins("https://localhost:5002/");
});
});
});
}
// 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.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
//实体框架
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“ConnStr”));
//为了身份
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
//添加身份验证
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme=JwtBearerDefaults.AuthenticationScheme;
})
//添加Jwt承载
.AddJwtBearer(选项=>
{
options.SaveToken=true;
options.RequireHttpsMetadata=false;
options.TokenValidationParameters=新的TokenValidationParameters()
{
validateisuer=true,
ValidateAudience=true,
Validudience=配置[“JWT:Validudience”],
ValidisUser=配置[“JWT:ValidisUser”],
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(配置[“JWT:Secret”]))
};
services.AddCors(选项=>
{
options.AddPolicy(“CorsPolicy”,
生成器=>
{
建筑商。来源(“https://localhost:5002/");
});
});
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
附录UseCors(“公司政策”);
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}
我在执行时遇到以下错误:
在'https://localhost:5001/api/District/“起源”https://localhost:5002'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源
有人能提出一个改变,使这项工作吗?我已经去了MS文档,但这就像试图用阿拉伯语读古兰经……对
UseCors
的调用必须放在UseRouting
之后,但在UseAuthorization
之前:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
参考:
此代码适用于我:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options => options.AddPolicy(
"_mypolicy", builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
)
);
}
// 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.UseCors("_mypolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
试着把app.UseCors(“CorsPolicy”)代码>在
app.UseAuthorization()之前代码>。我根据您的答案进行了更改,但仍然与我原来帖子中的消息有误。我可以从邮递员那里一无所获。我也遇到了一个错误,并且已经尝试了所有的方法