Lan*_*nce 3 jquery watermark cors .net-core angular
我使用 Angular 在与前端 html 站点不同的域上托管我的 dotnet core 3.1 API。我正在使用 jquery 水印插件在图像上添加水印,但有时图像显示正常,但未添加水印。当我检查控制台时,它显示错误,指出对图像的访问被 CORS 策略阻止。我的 API 都工作正常,没有 cors 问题。
我的 API 设置中做错了什么?看起来正常的静态文件可以工作,但是使用canvas.toDataURL()获取图像时提示错误。
我配置了 Startup.cs 配置方法,如下所示:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = ctx => {
ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
},
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")),
RequestPath = new PathString("")
});
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{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");
}
});
}
Run Code Online (Sandbox Code Playgroud)
我尝试将配置添加到 UseStaticFiles 但它仍然不起作用
下面的信息是我的请求标头和响应标头
GET //imageUploaded/banner_002_bb9d.jpg HTTP/1.1,
Origin:,
Referer:,
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/80.0.3987.163 Safari/537.36
Run Code Online (Sandbox Code Playgroud)
Accept-Ranges: bytes
Content-Length: 119395
Content-Type: image/jpeg
Date: Fri, 10 Apr 2020 12:12:14 GMT
ETag: "1d600678e1fa163"
Last-Modified: Sun, 22 Mar 2020 16:33:02 GMT
Server: Microsoft-IIS/10.0
Warning: 113
X-Powered-By: ASP.NET
Run Code Online (Sandbox Code Playgroud)
Lan*_*nce 13
经过一些测试,我找到了可行的解决方案。
此代码适用app.UseStaticFiles();于静态文件的正常服务。但是,当使用 xhr 请求下载静态文件时,需要进行 cors 设置才能跨域工作。
下面的代码是让它工作所需的代码
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = ctx => {
ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
},
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
3188 次 |
| 最近记录: |