欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.Net Core跨域处理

程序员文章站 2024-01-29 17:51:58
...

.Net Core跨域处理

查看官方文档

https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2

分两部分处理跨域

  • ConfigureServices里添加
services.AddCors(options =>

        {

            options.AddPolicy(MyAllowSpecificOrigins,

            builder =>

            {

                builder.WithOrigins("http://example.com",

                                    "http://www.contoso.com");

            });

        });
  • Configure里添加
app.UseCors(MyAllowSpecificOrigins);

问题1:

前端调试是还是存在跨域问题

解决(谷歌为例):  

options.AddPolicy(MyAllowSpecificOrigins,

                builder =>

                {

                    builder.WithOrigins("http://example.com",

                                        "http://www.contoso.com","http://192.168.66.149:81");

                });

或者这里可以之前全部放开域检测  

 options.AddPolicy(MyAllowSpecificOrigins,

                builder =>

                {

                    builder.WithOrigins("http://example.com",

                                        "http://www.contoso.com").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));;

                });

问题2:

不全部放开域检测,不同的action跨域控制问题

官方文档说[EnableCors]写在方法上面

这里说明一下

ConfigureServices按照上面官方文档写时,action最上一行不需要写[EnableCors]也可以

ConfigureServices这么写时

services.AddCors(options =>

            {

                options.AddDefaultPolicy(

                builder =>

                {



                    builder.WithOrigins("http://example.com",

                                        "http://192.168.66.149:81");

                });

                options.AddPolicy(MyAllowSpecificOrigins,

                builder =>

                {

                    builder.WithOrigins("http://example.com",

                                        "http://www.contoso.com","http://192.168.66.149:81");

                });

            });

[EnableCors]代表默认策略

[EnableCors("_myAllowSpecificOrigins")]

.Net Core跨域处理

这样区别两种策略

如果方法前没有写默认的是[EnableCors("_myAllowSpecificOrigins")]