概念理解

CORS:跨域资源共享

简单请求

CORS详解 - 图1

非简单请求

CORS详解 - 图2

一图说明

image.png

手动尝试

客户端

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title></title>
  6. </head>
  7. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  8. <body>
  9. <h1>这是标题</h1>
  10. <button onclick="SendCors1()">SendCORS !! </button>
  11. <script>
  12. function SendCors1() {
  13. $.ajax({
  14. url: 'https://localhost:7178/home/',
  15. method: 'GET',
  16. headers:{
  17. 'aa':'3232' //自定义的header表示为非简单请求
  18. },
  19. success: (res) => {
  20. console.warn('success', res);
  21. alert(res.content);
  22. }
  23. });
  24. }
  25. </script>
  26. </body>
  27. </html>


服务端

  1. var builder = WebApplication.CreateBuilder(args);
  2. // Add services to the container.
  3. builder.Services.AddControllers();
  4. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  5. builder.Services.AddEndpointsApiExplorer();
  6. builder.Services.AddSwaggerGen();
  7. //步骤一
  8. //CORS配置
  9. string pname = "testpolicy";
  10. builder.Services.AddCors(options =>
  11. {
  12. options.AddPolicy(name: pname,
  13. policy =>
  14. {
  15. policy.AllowAnyHeader().AllowAnyOrigin();
  16. });
  17. });
  18. var app = builder.Build();
  19. //...
  20. //步骤二
  21. //使用跨域资源共享
  22. app.UseCors(pname);
  23. app.MapControllers();
  24. app.Run();


http请求示例

image.png

参考

阮一峰-跨域资源共享 CORS 详解 MDN-跨源资源共享(CORS) fetch 在 ASP.NET Core 中启用跨源请求 (CORS) Getting started with the IIS CORS Module