This will be a duplicate. How does the Access-Control-Allow-Origin header work? but the method there also does not work for me. I hope that I just missed something.
I am trying to get the header Access-Control-Allow-Origin
in my answer from my .NET API for the kernel, which I am accessing through AJAX.
I have tried several things. All, unless otherwise indicated, were in the file Startup.cs
.
Method 1
According to Microsoft Documentation :
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetService<DbContext>().Database.Migrate();
serviceScope.ServiceProvider.GetService<DbContext>().EnsureSeedData();
}
}
app.UseCors(builder => builder.WithOrigins("https://localhost:44306").AllowAnyMethod());
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
Audience = Configuration["Authentication:AzureAd:Audience"],
});
app.UseMvc();
}
Method 2
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowWebApp",
builder => builder.AllowAnyMethod()
.AllowAnyMethod()
.AllowAnyOrigin()));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowWebApp");
}
I also tried adding to [EnableCors("AllowWebApp")]
both the controller and the method.
From the postman I get:
→ gzip
content-type → text/plain; = UTF-8
→ , 25 2017 04:51:48 GMT
→ Kestrel
→ 200
→ Accept-Encoding
x-powered by → ASP.NET
x-sourcefiles → =? UTF-8? B? [REDACTED]
Chrome .
, , , Authorize
. (, , )
, - ? 1.1.0.
JS Stub
function getContactPreviews(resultsCallback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
resultsCallback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.open("GET", "https://localhost:44357/api/User/ContactsPreview", true);
xmlhttp.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("AuthorizationToken"));
xmlhttp.send();
}
-
[Authorize]
[Route("api/[controller]")]
public class UserController : ApiController
{
[HttpGet(nameof(ContactsPreview))]
[EnableCors("AllowWebApp")]
public IEnumerable<Customer> ContactsPreview()
{
}
}