我不确定自己缺少什么,但似乎无法使我的CORS策略与.NET Core 3.1和Angular 8客户端一起使用。
Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// ...
// Add CORS policy
services.AddCors(options =>
{
options.AddPolicy("foo",
builder =>
{
// Not a permanent solution, but just trying to isolate the problem
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
// Use the CORS policy
app.UseCors("foo");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
错误消息客户端:
Access to XMLHttpRequest at 'https://localhost:8082/api/auth/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
参考文献:
https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785
答案 0 :(得分:20)
Web API正在使用app.UseHttpsRedirection()
;如果请求的客户端不是基于CORS
的,则会导致https
问题。因此,为了与http
客户一起使用它,我们需要注释或删除该行。
此问题与CORS
无关,https引起了此问题,但抛出错误却表明了CORS。
答案 1 :(得分:5)
首先#include <curl/curl.h>
#include <errno.h>
#include <iostream>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int upload(const std::string &filename, const std::string &url) {
CURL *curl;
CURLcode res;
struct stat file_info;
curl_off_t speed_upload, total_time;
FILE *fd;
curl_mime *form = NULL;
curl_mimepart *field = NULL;
struct curl_slist *headerlist = NULL;
static const char buf[] = "Expect:";
fd = fopen(filename.c_str(), "rb");
if (!fd) {
printf("unable to open file: %s\n", strerror(errno));
return 1;
}
if (fstat(fileno(fd), &file_info) != 0) {
printf("unable to get file stats: %s\n", strerror(errno));
return 2;
}
std::cout << "filename : " << filename << ":"
<< std::endl;
std::cout << "url : " << url << std::endl;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
form = curl_mime_init(curl);
/* Fill in the file upload field */
field = curl_mime_addpart(form);
curl_mime_name(field, "file");
curl_mime_filedata(field, filename.c_str());
headerlist = curl_slist_append(headerlist, buf);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_MIMEPOST, form);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &speed_upload);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
printf("Speed: %" CURL_FORMAT_CURL_OFF_T
" bytes/sec during %" CURL_FORMAT_CURL_OFF_T ".%06ld seconds\n",
speed_upload, (total_time / 1000000),
(long)(total_time % 1000000));
}
}
return 0;
}
int main(int argc, char **argv) { return upload(argv[1], argv[2]); }
,然后app.UseRouting();
按如下所示更改您的app.UseCors("foo");
方法:
Configure
对我有用!
答案 2 :(得分:5)
在添加Cors服务时,请确保在.SetIsOriginAllowed((host) => true)
之后加上.WithOrigins("http://localhost:4200")
services.AddCors(options => {
options.AddPolicy("mypolicy",builder => builder
.WithOrigins("http://localhost:4200/")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader());
});
答案 3 :(得分:2)
我遇到了这个错误,我曾经使用 CLI .net 核心运行我的项目,但它没有工作,但是当我使用 IIS Express Visual Studio 运行该项目时,它没有出现 CORS 问题,重定向到 https 时会发生这种情况Startup.css 类的 Configure 方法中的中间件 app.UseHttpsRedirection();,就像 Waseem Ahmad Naeem 提到的那样。
总是访问 .Net Core Middleware 顺序是好的,但将它们放在不好的顺序可能会给应用程序带来性能问题,甚至使事情无法按预期工作。 中间件文档如下。
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0
答案 4 :(得分:1)
可能存在多个导致CORS错误的问题。确保首先正确配置CORS。您可以通过以下方式进行配置:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
然后在Startup.cs文件的Configure()中,以下应该是中间件的顺序:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json", "API");
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
如果您已将.NET Core应用程序配置为在HTTPs URL上运行,那么请确保也为Angular的API请求调用该应用程序的https URL。
如果要从Angular调用HTTP URL并在HTTPs上运行.NET核心应用程序,请删除app.UseHttpsRedirection()
中间件。
要使用app.UseHttpsRedirection()
,请在HTTPs URL上运行.NET核心并从角度请求HTTPs,或者在HTTP URL上运行.NET核心并从角度请求HTTP(在这种情况下,.NET应用程序只能在HTTP上运行。不应配置为同时在HTTP和HTTP上运行。
以上情况最有可能解决您的问题。
答案 5 :(得分:0)
尝试这个工具
https://www.nuget.org/packages/Microsoft.AspNetCore.Cors/ 使用此功能,您可以在.net核心应用程序中启用/禁用cors
答案 6 :(得分:0)
因为您将localhost用作http://localhost:4200
,然后尝试在您的配置中设置它:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
{
build.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ... other code is omitted for the brevity
}
}
和Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("ApiCorsPolicy");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
答案 7 :(得分:0)
我通过将EnableCors添加到控制器中解决了我的问题
[EnableCors("MyPolicy")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
答案 8 :(得分:0)
对UseCors的调用必须放在UseRouting之后,但必须在UseAuthorization之前。有关更多信息,请参见https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
答案 9 :(得分:0)
在我的情况下,这与标头的Content-Type是application / json有关。
CORS仅允许那些Content-Type标头:
application / x-www-form-urlencoded
multipart / form-data
文本/纯文本
答案 10 :(得分:0)
我也遇到了同样的问题,我发现自定义中间件必须放在useCors()之后
app.UseHttpsRedirection();
app.UseAuthentication();
app.UsePathBase("/api");
app.UseRouting();
app.UseCors("AllowSpecificOrigins");
app.UseMiddleware<CountryMiddleware>();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});