rum*_*umi 10 c# rest asp.net-web-api2 .net-core
在我的asp.net核心web api中,我根据MS文档中的文章配置了Cors .web api应用程序正在使用Windows身份验证(未启用匿名身份验证).创建了Cor的策略,并在下面添加了中间件startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Enable CORS policy
app.UseCors("CorsPolicy");
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
还应用了每个控制器级别的策略
[EnableCors("CorsPolicy"), Route("api/[controller]")]
public class LocationController : BaseController<Location>
{
//code
}
Run Code Online (Sandbox Code Playgroud)
选项请求未获授权.请求和响应看起来像
我已经看到了类似的问题并尝试了几乎所有解决方案,但选项请求仍然失败.
Nir*_*tel 10
1) 在 launchSettings.json 文件(开发设置文件)中将允许 Windows 和匿名身份验证标志设置为 true。
匿名身份验证:需要允许飞行前选项请求。
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iis":
...
}
Run Code Online (Sandbox Code Playgroud)
2) 在配置服务方法中添加Cors策略。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy("MyCustomCorsPolicyName",
builder => builder.WithOrigins("http://YourDomainName/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud)
3:将 CORS 中间件添加到您的 Web 应用程序管道中以允许跨域请求。
public void Configure(IApplicationBuilder app)
{
....
app.UseCors("MyCustomCorsPolicyName");
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
4) 在控制器顶部添加授权属性以强制客户端发送凭据
[Authorize]
public class MyAPIController : ControllerBase
{
...
}
Run Code Online (Sandbox Code Playgroud)
5) 在 JQuery 或您使用的任何客户端中,将 withCredentials 属性标志设置为 true
$.ajax({
type: "POST",
datatype: "json",
url: "YourApiUrl",
xhrFields: {
withCredentials: true
}
Run Code Online (Sandbox Code Playgroud)
这在我使用 .net core 2.2、带有 Windows 身份验证的 IIS Express 的开发环境中对我有用。
您可能需要阅读以下主题:https : //github.com/aspnet/CORS/issues/60。您可以将匿名和NTLM混合使用,以使您的CORS预检不被拒绝(因为它们不包含Windows凭据)。IIS在进入中间件之前就已经处理过NTLM身份验证,因此这很可能是IIS。您可能需要允许匿名COR进行飞行前检查。
| 归档时间: |
|
| 查看次数: |
4196 次 |
| 最近记录: |