1

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.

2
  • copy and show headers from request and response Commented Sep 30, 2016 at 7:04
  • I was able to overcome the issue, see edits for details. Commented Oct 4, 2016 at 10:49

3 Answers 3

2

If you are looking to enable CORS on web api core side then follow these steps-

First, add dependency in project.json - "Microsoft.AspNetCore.Cors": "1.0.0",

then enable CORS in startup.cs like this-

app.UseCors(builder => {
    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});

In case if you want to restrict to specific origin then you can do like this-

app.UseCors(builder => builder.WithOrigins("example.com"));

You can find more information about CORS here

See if this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

In your Configure method, you forgot to allow any methods, so the POST request failed. Your Configure method should look like this :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
       ..
        app.UseCors(builder =>
        builder.WithOrigins("https://localhost:44352/")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        );
      ..
 }

And you forgot to send credentials, if you don't and if you use anthentication cookies or anti XHRF they are not going to be sent :

var request = $http({
    method: "post",
    url: serviceBase + "api/token",
    data:
        {
            username: "DemoUser",
            password: "Password"
        },
    withCredentials: true
    }
});

Comments

0

You have to put these:

headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods': 'GET, POST'
}

In server response, not client request

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.