我有一个启用了CORS的控制器。
[EnableCors(Startup.CORS_POLICY_EXTERNAL)]
public class MasterController : Controller
{
[HttpGet]
public IActionResult TestaConnessione()
{
return Ok();
}
}
只需进行简单的获取操作:
fetch("url/MasterController/TestaConnessione")
调用方获取 header CORS “Access-Control-Allow-Origin” missing
但如果调用方使用 iframe,则一切正常:
<iframe name="ifrReport" id="ifrReport"></iframe>
<script type="text/javascript">
(function () {
let form, input;
form = document.createElement("form");
form.action = "URL";
form.target = "ifrReport";
form.method = "POST";
document.body.appendChild(form);
form.submit();
})();
</script>
这是启动配置:
public const string CORS_POLICY_EXTERNAL = "CORS_POLICY_EXTERNAL";
public const string CORS_POLICY_LOCAL = "CORS_POLICY_LOCAL";
services.AddCors(options =>
{
options.AddPolicy(name: CORS_POLICY_EXTERNAL,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
options.AddPolicy(name: CORS_POLICY_LOCAL,
builder =>
{
builder.WithOrigins("http://localhost")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseMiddleware<AuthenticationMiddleware>();
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
app.UseAuthorization();