使用Angular 8消耗ASP NET Core 3.1 Web Api时出现CORS策略问题 [英] CORS policy issue when consuming ASP NET Core 3.1 Web Api by Angular 8

查看:53
本文介绍了使用Angular 8消耗ASP NET Core 3.1 Web Api时出现CORS策略问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发Angular 8,ASP NET Core Web Api Web应用程序时,我遇到了CORS策略问题.我的角度应用程序正在http://localhost:4200上运行创建了一项与Web Api进行通信的服务.看起来如下

I have encountered issue with CORS policy when developing Angular 8, ASP NET Core Web Api web application. My angular app is running on http://localhost:4200 There is one service created for communication with Web Api. It looks as follows

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  apiUrl: string = "";
 

  constructor(private http: HttpClient) {
 
    this.apiUrl = 'https://localhost:44316';
  }

 
  login(Username: any, Password: any){  
    return this.http.post<Observable<ResultItem<AuthenticationResponse>>>(this.apiUrl + "/api/User/Authenticate", {Username: Username, Password: Password});
  }
 
}

服务随后在组件中被调用,但它只是被注入,并与订阅方法一起使用.

Services is later called within component, but it is simply injected, and used with subscribe method.

 onLogin(){  
    this.authenticationService.login(this.loginFormValues.username.value, this.loginFormValues.password.value).subscribe(
       result => {}); 
  }

Web Api在https://localhost:44316/上单独运行从Angular调用的方法的端点如下所示:

Web Api is running seperatly, on https://localhost:44316/ End point for the method called from Angular looks as follows:

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IUserService userService;

    public UserController(IUserService userService)
    {
        this.userService = userService;
    }


    [HttpPost("Authenticate")]
    public async Task<IActionResult> Authenticate(AuthenticationModel model)
    {
        return Ok(await userService.Login(model));
    }
}

我最关心的是我的启动文件.到目前为止,我尝试更改那里的CORS设置,但没有成功的结果.Startup.cs文件的代码如下.

What I am most concerned about is my Startup file. So far, I have tried to change the CORS setting there, but with no successful results. Code of the Startup.cs file looks as follows.

快速注释:

ConfigureServices方法中的两行代码使用了我的一些外部函数,其目的是:

Two lines of code within ConfigureServices method use some of my external functions, and their purpose is to:

  • AddSubstracture:将所有存储库注册为瞬态并注册DbContext.

  • AddSubstracture: registers all repositories as transients and registers DbContext.

AddApplication:将存储库上一层的服务注册为瞬态

AddApplication: registers services which are one layer above repositories as transients

Startup.cs代码如下

Startup.cs code looks as follows

public class Startup
{
    private IServiceCollection _services;

    public Startup(IConfiguration configuration, IWebHostEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
        SportFacilityUnitSettings = configuration.Get<SportFacilityUnitSettings>();
    }

    public IConfiguration Configuration { get; }
    public IWebHostEnvironment Environment { get; }
    public SportFacilityUnitSettings SportFacilityUnitSettings { get; }

    public void ConfigureServices(IServiceCollection services)
    {
         
        services.AddCors();
        services.AddMvc(option => option.EnableEndpointRouting = false);

        services.AddSubstructure(Configuration, Environment, SportFacilityUnitSettings);
        services.AddApplication(); 
        services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>();

        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);
         
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);

        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        }); 
        services.AddControllers().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
        services.AddHttpContextAccessor();

       
        _services = services;
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors(
         options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
     );
        app.UseMvc();
        app.UseHsts();
        app.UseMiddleware<JwtMiddleware>(); 
        app.UseAuthentication();
        app.UseRouting();  
        app.UseHttpsRedirection();  
        app.UseStaticFiles();
        app.UseAuthorization();  
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers(); 
        });

    }
}

当我按下登录按钮(目的是发送请求)时,我在Web浏览器控制台中收到以下错误.

When I hit the login button, which purpose is to send the request, I receive following error in web browser console.

CORS策略已阻止从源"http://localhost:4200"访问"https://localhost:44316/api/User/Authenticate"处的XMLHttpRequest:无"Access-Control-Allow-Origin"标头出现在请求的资源上.

Access to XMLHttpRequest at 'https://localhost:44316/api/User/Authenticate' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

最奇怪的事情是,当我调试它并在Api层中设置一个断点时,调试器将其击中,然后它进入服务层,并在Authentication方法内部某处失败.

The weirdest thing about it, is when I debug it, and set up a breakpoint in Api layer, debugger hits it, then it enters the service layer and fails somewhere inside Authentication method .

推荐答案

转到托管应用程序的IIS,并检查是否正确设置了以下信息.

Go to IIS where your application is hosted and check if you have set the below information right.

#Step 1 :IIS->HTTP响应标头]

#Step 1 : IIS --> HTTP Response header]

#Step 2::在IIS下托管的API应用中设置4个字段

#Step 2 : : Setting 4 fields in your API app hosted under IIS

#步骤3:如果上述两个步骤不起作用,请确保您遵循msdn信息为您的应用启用了cors https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view = aspnetcore-3.1

#Step 3: If the above 2 steps does not work, make sure you follow the msdn information to enable cors for your application https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

第4步::调查您在Web API中使用的标头信息,以及IIS设置是否允许该标头信息(如步骤1所述)

Step 4 : : Investigate the header information you are using in your web API and if that's allowed under your IIS setting (as mentioned in Step 1)

第5步::在您的身份验证方法中放置一个断点,以查看失败的原因和原因.您也可能会从此错误信息中获得更多线索.

Step 5 : : Place a breakpoint in your authenticate method to see where and why its failing. You may get more clue from this error information as well.

第6步:尝试从前端将CrossDomain设为true.

Step 6 : Try enabling CrossDomain to true from your front end.

第7步::尝试同时为应用程序(调用应用程序和被调用应用程序)启用https

Step 7 : Try enabling https for both the application (calling application and called application)

这篇关于使用Angular 8消耗ASP NET Core 3.1 Web Api时出现CORS策略问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆