I have an WEB API Core hosted in a different local host and I am trying to access it from my MVC Core app through AngularJS $http service.
Here is my homeController.js
app.controller("homeController", function ($scope, $http) {
$scope.accessToken = "";
var serviceBase = "https://localhost:44351/";
var request = $http({
method: "post",
url: serviceBase + "api/token",
data:
{
username: "DemoUser",
password: "Password"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods': 'GET, POST'
}
});
request.success(function (result) {
$scope.accessToken = result;
});
});
To enable cross origin calls in the Startup.cs of the WEB API Core
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
..
app.UseCors(builder =>
builder.WithOrigins("https://localhost:44352/")
.AllowAnyHeader()
);
..
}
Despite of this I am still getting this error in chrome.
XMLHttpRequest cannot load https://localhost:44351/api/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44352' is therefore not allowed access.
I am able to call api from Postman client.
Any steps I missed in this? Please help.
Fixes I did for this:
In the WebAPI project web.config file
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://localhost:xxxxx" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
...
In StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
// services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ app.UseCors(builder =>
builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);}
Chrome didn't allowed me to use * in Access-Control-Allow-Origin
field.
Also added "Microsoft.AspNetCore.Cors": "1.0.0"
in project.json
Thanks everyone for help. I am really noob at this.
See Question&Answers more detail:
os