Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

javascript - Enabling CORS in Web API Core and Angular JS

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...