У меня ASP.net WebApi Core с включенным CORS.Это шаблон Visual Studio ASP.net Core Web API.Единственный добавленный код - это код для поддержки CORS:
public void ConfigureServices(IServiceCollection services)
{
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.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
/* other stuff */
app.UseCors(builder => builder
.WithOrigins("https://localhost:44310")
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMvc();
}
}
Мой API размещен на localhost: 44361 и mycalling WEB на localhost: 44310 .Есть разные порты, поэтому мой запрос приходит из разных источников.Вот почему в ответе должен быть заголовок Access-Control-Allow-Origin .Это отсутствует, и я вижу ошибку в консоли браузера:
Access to fetch at 'https://localhost:44361/api/values' from origin 'https://localhost:44310' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
В чем проблема?
Заголовки запроса:
GET https://localhost:44361/api/values HTTP/1.1
Host: localhost:44361
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Origin: https://localhost:44310
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
Accept: */*
Referer: https://localhost:44310/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Заголовки ответа:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
X-SourceFiles: =?UTF-8?B?RDpcRGV2ZWxvcG1lbnRcQyNfcHJvZ3JhbW1pbmdcU0FNUExFU1xDb3JzQXBpU2ltdWxhdG9yXENvcmVBcGlcYXBpXHZhbHVlcw==?=
X-Powered-By: ASP.NET
Date: Thu, 16 May 2019 08:37:54 GMT