我正在尝试从静态HTML文件向ASP.NET Core 2.2 Web API发出本地发布请求。 CORS中间件工作正常,我可以做一个简单的get请求。我最终需要从chrome扩展程序中发出此发布请求。从一开始我就一直在使用ASP.NET,这是我第一次尝试Core解决方案,我为克服所有障碍感到困惑,尤其是这个难题。我的提取语法有问题吗?
这是基于此的我的CORS配置: https://enable-cors.org/server_aspnet.html
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder => builder.WithOrigins("*"));
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
fetch call in local static html file:
fetch ('http://localhost:49828/Bookmark', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({ ID: 0, Name: 'google', URL: 'google.com', Tags: '' })
})
here's the raw request from Fiddler:
OPTIONS http://localhost:49828/Bookmark HTTP/1.1
Host: localhost:49828
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
console log from chrome:
Access to fetch at 'http://localhost:49828/Bookmark' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
console log from firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49828/Bookmark. (Reason: missing token ‘content-type’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
答案 0 :(得分:0)
已经有一段时间了,但是我不确定.WithOrigins(“ *”)是通配符的有效方法。您是否尝试过使用.AllowAnyOrigin()?甚至更好(从安全角度出发),将WithOrigins与HTML文件的托管主机一起使用。如果这是本地地址,那么它将是您从中提供HTML页面的本地主机地址(我认为它与您的API不同)。
类似(其中1234是托管HTML的实际本地端口)。
app.UseCors(builder => builder.WithOrigins("https://localhost:1234"));
如果AllowAnyOrigin()用于测试,可以。但是不要在生产中使用它。 Microsoft认为这是不安全的配置(请参见https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#set-the-allowed-origins)。产品中始终使用命名起源。