【发布时间】:2019-06-20 18:44:30
【问题描述】:
我在 IIS 上托管了 .NET Core WebAPI,我在 startup.cs 中启用了 CORS。
从我的 Angular 应用程序向 API 发出请求时,请求失败,我收到此错误
“从源 'https://test-apps2.contractorconnection.com' 访问 XMLHttpRequest 在 'https://test-api.contractorconnection.com/ERCore_Service/api/LandingPage/Authenticate/Austin.Born/ERCore' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有 'Access-Control-Allow-Origin' 标头存在于请求的资源上。”。
当直接从浏览器或邮递员发出请求时,请求完成并且我得到了我的数据。
我尝试了很多答案,修改了 web.config,并在 Startup.cs
中指定了允许的来源我在这里遗漏了什么或做错了什么?
Startup.cs 下面
public void ConfigureServices(IServiceCollection services) {
// //For JWT Auth
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddScoped<ILandingPage, DAL_LandingPage>();
services.AddScoped<IDetails, DAL_EstimateDetailPage>();
services.AddScoped<IQueueDetailsPage, DAL_QueueDetails>();
services.AddScoped<IAdminDetailPage, DAL_AdminDetailPage>();
services.AddScoped<IAdminCatSelTab, DAL_AdminCatSel>();
services.AddScoped<IApplicationSecurityTab, DAL_ApplicationSecurityTab>();
//services.AddCors();
services.AddCors(o => o.AddPolicy("MyPolicy", builder => {
builder.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("https://test-apps2.contractorconnection.com", "https://test-apps2.contractorconnection.com/ERCore", "http://localhost:54807/")
.AllowCredentials();
}));
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ContractResolver
= new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
services.AddDbContext<PrismDataContext1>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
//app.UseCors(builder => builder.WithOrigins("http://localhost:4200", "https://cc-er-dev-api.primussoft.com", "https://test-apps2.contractorconnection.com", "https://apps2.contractorconnection.com").AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseCors("MyPolicy");
app.UseOptions();
//For JWT Auth
app.UseAuthentication();
app.UseMvc();
}
控制器端点
[HttpGet]
[Route("api/LandingPage/Authenticate/{webLogin}/{appName}")]
[HttpOptions]
public JsonResult AuthenticateUser(string webLogin, string appName) {
string connectionString = _config.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
Auth auth = new Auth(connectionString);
User obj = new User();
try {
bool hasAccess = auth.Load(webLogin, appName);
obj.Name = auth.Name;
obj.ResourceTypeName = auth.ResourceTypeName;
obj.ClassificationName = auth.ClassificationName;
obj.Login = auth.Login;
obj.ResourceID = auth.ResourceID;
obj.DetailID = auth.DetailID;
obj.ApplicationID = auth.ApplicationID;
obj.ResourceTypeID = auth.ResourceTypeID;
obj.ClassificationID = auth.ClassificationID;
obj.SecurityFeatures = auth.FeatureAccess;
obj.CurrentLanguageDescription = auth.CurrentLanguageDescription;
obj.CurrentLanguageID = auth.CurrentLanguageID;
var tokenString = BuildToken(obj);
obj.Token = tokenString;
Response.Headers.Add("Access-Control-Allow-Origin", "https://test-apps2.contractorconnection.com");
return Json(obj);
} catch (Exception ex) {
string ac = ex.Message;
return Json(obj);
}
}
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="false">
<add origin="*" allowed="true" />
</cors>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\ERCore_Service.exe" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
【问题讨论】:
-
IIS 有一个 CORS 模块。
-
@LexLi 我安装了模块,没有成功
-
模块不会自动工作,除非你给出有效的配置,docs.microsoft.com/en-us/iis/extensions/cors-module/…
-
@LexLi 仍然不起作用,我将我的 Web.config 添加到帖子中进行验证。
-
此问题可能与我们服务器上的另一层安全性有关。我有另一个开发人员正在检查某事/说他知道出了什么问题。如果问题不在于代码或 IIS,我今天或明天会有答案。
标签: iis asp.net-core .net-core