A cross-origin request is a mechanism allowing a website to load a resource located from a domain other than that in which the site is located. This mechanism is strictly supervised for security reasons. It is possible to obtain Cross-Origin requests with the Angular frame. The server receiving its requests must first authorize it to then be able to send.
The objective is to secure the Web API and ensure that no one can consume the it without prior authorization.
Web API Config
In the Startup.cs file, you need to tell the Web API the list of domains that has right to interact with it and the authorized HTTP verbs to use.
In the ConfigureService method we add this configuration:
public void ConfigureServices(IServiceCollection services)
{
var appSettingsSection = Configuration.GetSection("AppSettings");
var appSettings = appSettingsSection.Get<AppSettings>();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins(appSettings.OriginUrl)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
.....
}
Eventually, don’t forget to add a json file configuration called appsettings.Release.json for Release Build that will represent your production environment config.
![](https://learntechnologies.fr/wp-content/uploads/2020/04/Capture-2.png)
So, your json config files will contain the OriginUrl that represent your Angular project URL for each environment.
Don’t forget to add the AppSettings class which asp.net core will use it to serialize the AppSettings config file.
public class AppSettings
{
public string OriginUrl { get; set; }
...
}
Finally, in WebApi part, we need to add app.UseCors(“CorsPolicy”) in Configure method and add the attribute [EnableCors(“CorsPolicy”)] above controllers.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
..........
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
app.UseMvc();
}
Angular Configuration
In Angular project under src/environments folder, you have 2 files called environment.prod.ts and environment.ts. The first on is for production environment and the second one is for development environment.
Inside this 2 files, you can put your Web API base URL switch environment. This avoids redundant code, so it looks like:
environment.ts
import { HttpHeaders } from '@angular/common/http';
export const environment = {
production: false,
apiURL: "https://localhost:44372/api",
}
};
and environment.prod.ts:
import { HttpHeaders } from '@angular/common/http';
export const environment = {
production: false,
apiURL: "https://{{productionurl}}/api",
}
};
Finally, when you run the project :
ng serve --o
In order to deploy you project in production environment, please see my post Deploy Angular 8 App From Visual Studio Code to Azure
Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.