在Web API Core和Angular JS中启用CORS

时间:2016-09-30 06:59:19

标签: javascript angularjs asp.net-core cors asp.net-core-webapi

我有一个WEB API Core托管在不同的本地主机上,我试图通过AngularJS $ http服务从我的MVC Core应用程序访问它。

这是我的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;
});
});

在WEB API Core的Startup.cs中启用跨源调用

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()
        );
      ..
 }

尽管如此,我仍然在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.

我可以从Postman客户端调用api。 我错过了这个步骤吗?请帮忙。

我为此做了的修复

在WebAPI项目 web.config 文件

<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>
...

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不允许我在Access-Control-Allow-Origin字段中使用*。

还在project.json

中添加了"Microsoft.AspNetCore.Cors": "1.0.0"

感谢大家的帮助。我真的很不错。

3 个答案:

答案 0 :(得分:2)

如果您希望在web api核心端启用CORS,请按照以下步骤进行操作 -

首先,在project.json中添加依赖项 - "Microsoft.AspNetCore.Cors": "1.0.0",

然后在startup.cs中启用CORS,就像这样 -

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

如果您想限制为特定原点,那么您可以这样做 -

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

您可以找到有关CORS here

的更多信息

看看这是否有帮助。

答案 1 :(得分:1)

在Configure方法中,您忘记允许任何方法,因此POST请求失败。您的Configure方法应如下所示:

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

你忘了发送凭证,如果你不这样做,如果你使用的是认证cookie或反XHRF,那么它们将不会被发送:

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

答案 2 :(得分:0)

你必须把这些:

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

在服务器响应中,而不是客户端请求