【发布时间】:2019-08-15 17:15:50
【问题描述】:
我得到了 XmlHttpRequest 对象,我正在尝试将长 html 数据字符串发送到 Asp Net Core,以便从中提取内容 PDF 文件。但仍然获得 CORS 政策。即使我的标题中有“Access-Control-Allow-Origin”,这对我来说仍然是个问题。已经用 CORS 尝试了一切。为 Asp net Core 安装了 cors,没有任何改变。如果我使用本地的 HTML 文档,一切正常。
完全错误:
在“https://.../getInfoWindowPdf?”访问 XMLHttpRequest从 来源“https://...”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
function infoWindowPdf()
{
// Create request
let http = new XMLHttpRequest(); //XMLHttpRequest XDomainRequest
let url = backend + "getInfoWindowPdf?";
// Add in htmlContent header
let htmlContent = "<style>" + style +"</style>";
// Get needed content
let infoWindow = document.querySelector("#section-library-modal");
//Waits for backend to create file after all open it and remove created temporary files
http.onreadystatechange = function()
{
if(http.readyState == 4)
{
window.open(backend + 'InfoPdf?filePath=C:\\Projects\\Web\\WebSections\\wkhtmltopdf\\bin\\pdf-export\\' + sectionName + ".pdf", '_blank');
setTimeout(() => {getDBData('removepdf?filePath=C:\\Projects\\Web\\WebSections\\wkhtmltopdf\\bin\\pdf-export\\&filename=' + sectionName);}, 100);
}
};
http.open("POST", url, true);
http.setRequestHeader('Access-Control-Allow-Origin', '*');
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //application/x-www-form-urlencoded
http.send(params);
}
我的用于 CORS 的 Asp Net Core 启动配置。
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:5000",
"http://localhost:5000/websections/getInfoWindowPdf?"
).AllowAnyHeader().AllowAnyMethod();
});
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseCors(MyAllowSpecificOrigins);
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
编辑: 如果您想向后端项目发送一些数据,甚至不要尝试使用 Xmlhttprequest。直接使用后端即可。
【问题讨论】:
-
几天前我遇到了同样的问题。事实证明,这不是 CORS 问题;但这就是它的处理方式。就我而言,我还没有启动 asp.net 核心项目(是的,我有时就是这么笨)。
-
别以为它是 CORS 以外的东西。如果我从本地打开 HTML 文件,我的按钮将起作用。但是如果从 Asp 打开相同的 HTML 则会出现此错误。
-
您在 .net 核心应用程序中的 CORS 策略是什么?您应该在 startup.cs 中包含一些内容和/或设置您的策略的扩展。您的请求中不应包含任何内容,这不是必需的。
-
编辑了我的帖子。
-
您的错误消息,尽管您对它进行了截断,但显示您的来源以
https://开头,但您允许的所有来源都以http://开头。您似乎只是在可接受的来源列表中打错了字。
标签: javascript asp.net-core cors xmlhttprequest