1、配置服务端
在Startup文件中国配置Cors策略:
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()); });
启用CORS策略,可以在Startup文件中配置,也可以在具体的ApiController中配置,代码分别如下:
app.UseCors("default");
[Authorize] [EnableCors("default")] public class NavigationMenuController:Controller { private NavigationMenuService navigationMenuService; public NavigationMenuController(NavigationMenuService navigationMenuService) { this.navigationMenuService = navigationMenuService; } }
2、JQuery请求
$.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)); } });
红字是关键 ,值得注意的是需要配置 withCredentials,否则请求不会带上Cookie。
3、 axios请求
axios({ url: config.authority + "/api/xxxxxxxxxx?clientId=" + escape(config.client_id), method: "GET", withCredentials: true }).then(function (result) { if (result.success == undefined) { self.menuItems = result || []; } });
’