angular2: asp.net core service throws 'No acce

2019-07-23 04:02发布

I have any angular2 app accessing asp.net core webapi service. It is working if webapi iis configuration is (Properties\launchSettings.json):

"iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:12246/",
      "sslPort": 0
    }
  },

However, it throws the error once WindowsAuthentication is true and AnonymousAuthentication is false. The error:

XMLHttpRequest cannot load http://localhost:12246/api//values/getSettings. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

Any idea please?

1条回答
SAY GOODBYE
2楼-- · 2019-07-23 04:59

You are attempting to make a cross-origin request. This is permitted under the CORS specification, but requires configuration.

There are three steps to fixing this problem.

  1. Configure both web servers to use Windows Authentication (and disable anonymous authentication). That is, both the server hosting your Angular 2 app and the server hosting your ASP.NET Core WebAPI app must be configured.

  2. Enable CORS your ASP.NET Core WebAPI app:

    in your Startup.cs file:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        if (env.IsDevelopment())
        {
            app.UseCors(builder =>
            builder
            .WithOrigins("http://localhost:4200")  //<-- OP's origin
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
            );
        }
    
        app.UseMvc();
    }
    
  3. Have Angular 2 send your credentials along with its CORS request:

    import {Injectable}         from '@angular/core'
    import {Headers, Http, Response} from '@angular/http';
    import {Observable}         from 'rxjs/Observable';
    
    import 'rxjs/add/operator/toPromise';
    
    @Injectable()
    export class SomeAngularServiceThatCallsYourAPI{
    
        constructor(private http: Http) { }
    
        getApiData(): Promise<MyDataResult[]> {
    
            var apiUrl = 'http://localhost:12246/api//values/getSettings';
            return this.http.get(apiUrl,{
                withCredentials: true
            })
                .toPromise()
                .then(response => this.extractData(response) as MyDataResult[])
                .catch(this.handleError);
        }
    
    }
    

For further details, see my blog post.

查看更多
登录 后发表回答