简体   繁体   English

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

I have encountered issue with CORS policy when developing Angular 8, ASP NET Core Web Api web application.我在开发 Angular 8、ASP NET Core Web Api Web 应用程序时遇到了 CORS 策略问题。 My angular app is running on http://localhost:4200 There is one service created for communication with Web Api.我的 angular 应用程序在 http://localhost:4200 上运行 为与 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.服务稍后在组件中调用,但它只是被注入,并与 subscribe 方法一起使用。

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

Web Api is running seperatly, on https://localhost:44316/ End point for the method called from Angular looks as follows: Web Api 单独运行,在 https://localhost:44316/ 上,从 Angular 调用的方法的端点如下所示:

[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));
    }
}

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.到目前为止,我已经尝试在那里更改 CORS 设置,但没有成功。 Code of the Startup.cs file looks as follows. Startup.cs 文件的代码如下所示。

Quick note:快速说明:

Two lines of code within ConfigureServices method use some of my external functions, and their purpose is to: ConfigureServices 方法中的两行代码使用了我的一些外部函数,它们的目的是:

  • AddSubstracture: registers all repositories as transients and registers DbContext. AddSubstracture:将所有存储库注册为瞬态并注册 DbContext。

  • AddApplication: registers services which are one layer above repositories as transients AddApplication:将存储库上一层的服务注册为瞬态

Startup.cs code looks as follows Startup.cs 代码如下所示

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

    }
}

When I hit the login button, which purpose is to send the request, I receive following error in web browser console.当我点击用于发送请求的登录按钮时,我在 Web 浏览器控制台中收到以下错误。

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. CORS 策略已阻止从源“http://localhost:4200”访问“https://localhost:44316/api/User/Authenticate”处的 XMLHttpRequest:不存在“Access-Control-Allow-Origin”标头在请求的资源上。

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 .最奇怪的是,当我调试它并在 Api 层设置断点时,调试器命中它,然后它进入服务层并在 Authentication method 内的某处失败。

Go to IIS where your application is hosted and check if you have set the below information right.转到托管您的应用程序的 IIS 并检查您是否已正确设置以下信息。

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

IIS HTTP 响应头

#Step 2 : : Setting 4 fields in your API app hosted under IIS #Step 2 ::在 IIS 下托管的 API 应用程序中设置 4 个字段设置 IIS 值

#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 #Step 3:如果以上 2 个步骤不起作用,请确保您按照 msdn 信息为您的应用程序启用 cors https://docs.microsoft.com/en-us/aspnet/core/security/cors?view= aspnetcore-3.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)步骤 4 ::调查您在 Web API 中使用的标头信息,以及是否在您的 IIS 设置下允许(如步骤 1 中所述)

Step 5 : : Place a breakpoint in your authenticate method to see where and why its failing.步骤 5 ::在您的身份验证方法中放置一个断点以查看失败的位置和原因。 You may get more clue from this error information as well.您也可以从此错误信息中获得更多线索。

Step 6 : Try enabling CrossDomain to true from your front end.第 6 步:尝试从前端启用 CrossDomain 为 true。

Step 7 : Try enabling https for both the application (calling application and called application)第 7 步:尝试为应用程序(调用应用程序和被调用应用程序)启用 https

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IIS 中托管的 Angular 11 应用程序在调用 Asp.Net Web API 时会出现 CORS 问题 - Angular 11 app hosted in IIS giving CORS issue when calling Asp.Net Web API Asp.net Web API中子域的CORS策略的定义 - Definition of CORS Policy for sub domains in Asp.net Web API Call to my rest service from Angular app hosted in Asp.net core web server blocked by CORS policy - Call to my rest service from Angular app hosted in Asp.net core web server blocked by CORS policy Blazor ASP.Net Core 3.1 Web API 在发布时返回 404 错误 - Blazor ASP.Net Core 3.1 web API returning 404 error when published 将安全标头添加到 ASP.NET 核心 3.1 Web Api - Adding Security Headers to ASP.NET Core 3.1 Web Api .Net 3.1 API &amp; Angular 9 CORS 与 ZB909E8D0076FCB762542A045CA5BE7ZProxy - .Net 3.1 API & Angular 9 CORS with NGINX Proxy 无法在ASP.Net Core Web API中启用CORS - Can't enable CORS in ASP.Net Core web api 如何在ASP.NET Web API核心中全局启用CORS - How to enable CORS globally in ASP.NET web API core 在 ASP .NET Core 2.1 Web Api 中启用 CORS - Enable CORS in ASP .NET Core 2.1 Web Api 尝试将对象从asp.net Web API 2返回到Angular前端时出现CORS错误 - CORS Error when trying to return an Object from asp.net Web API 2 to Angular Front end
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM