【发布时间】:2019-05-31 03:31:43
【问题描述】:
我是 asp.net core 和 angular 的新手,我对 CORS 有一些问题。 我进行了搜索,几乎达到了我的目标,但对于特定案例我仍然有问题。
以下是遵循的步骤:
我从 this article
我创建了一个非常简单的 api 控制器来检索当前用户的角色,这是我的简化代码:
[Authorize()]
[Route("api/[controller]")]
public class PermissionController : Controller
{
private List<Tuple<string, string>> roles = new List<Tuple<string, string>> { new Tuple<string, string>("Admin", "Role_AutHab_Dev_Administrateur"), new Tuple<string, string>("Gest", "Role_AutHab_Dev_Gestionnaire") };
[HttpGet]
public IEnumerable<string> Get()
{
bool test = false;
List<string> lst = new List<string>();
foreach (var item in roles)
{
test = User.IsInRole(item.Item2);
if (test)
lst.Add(item.Item1);
}
return lst.ToArray();
}
To solved [this problem](https://github.com/aspnet/CORS/issues/60) with CORS in ASPNet Core, I allowed anonymous mode and windows mode in my c# project properties and configure my startup class like this :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseCors(o => o.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
此时,一切正常。
当我使用另一个为我提供业务数据的 API 时,问题就出现了。
当我在发布后使用 IIS Express(使用 Visual Studio)或使用 IIS 运行我的项目时,查询失败并在 chrome 控制台选项卡中出现 CORS 错误,但在 chrome 网络选项卡中工作正常!
像这样:
我认为问题来自匿名模式,因为我尝试通过权限控制器调用我的第二个 API,它工作正常(使用 Authorize 属性)但我不能对所有方法都这样做!
有什么想法吗?
【问题讨论】:
-
@FabianH。谢谢,但我已经阅读了这篇文章并应用了他的内容,您可以在屏幕截图中看到 CORS 工作正常
-
这是您的第一个屏幕截图,但不是您的第二个屏幕截图。两者有什么区别?
-
@FabianH。第一个是请求权限的 OPTION 查询,第二个是最终的 GET 查询,因为第一个返回 OK 并带有 CORS 详细信息标头
标签: c# angular iis asp.net-core cors