1. Configure the server
Configure the Cors policy in the Startup file:
IEnumerable<Client> clients= Configuration.GetSection("Clients").Get(typeof(IEnumerable<Client>)) as IEnumerable<Client>; List<string> urls = new List<string>(); foreach (var client in clients) { urls.AddRange(client.AllowedCorsOrigins); } services.AddCors(options => { options.AddPolicy("default", builder => builder.WithOrigins(urls.ToArray()) .AllowAnyHeader() .AllowCredentials() .AllowAnyMethod()); });
To enable CORS policy, you can configure it in the Startup file or in the specific ApiController. The codes are as follows:
app.UseCors("default");
[Authorize] [EnableCors("default")] public class NavigationMenuController:Controller { private NavigationMenuService navigationMenuService; public NavigationMenuController(NavigationMenuService navigationMenuService) { this.navigationMenuService = navigationMenuService; } }
2. JQuery request
$.ajax({ url: 'http://localhost:5000/api/Private/Values/Identity', type: 'GET', dataType: 'json', crossDomain: true, xhrFields: { withCredentials: true }, success: function (result) { $('#platformResult').val(JSON.stringify(result)); } });
The red letter is the key. It is worth noting that withCredentials needs to be configured, otherwise the request will not bring cookies.