c#解决浏览器跨域问题

时间:2023-03-09 17:26:59
c#解决浏览器跨域问题
1.浏览器为什么不能跨域?

浏览器有一个基本的安全策略--同源策略。为保证用户的信息安全,它对不同源的文档或脚本对当前文档的读写操作做了限制。域名,子域名,端口号或协议不同都属于不同源,当脚本被认为是来自不同源时,浏览器虽然会发出这个请求,但是会拦截响应内容。

2.解决跨域问题
CORS(Cross-Origin Resource Sharing,跨域资源共享),通过向http的请求报文和响应报文里面加入相应的标识告诉浏览器它能访问哪些域名的请求,直接在项目中安装Microsoft.AspNetCore.Cors即可使用。
(1).net core
在appsettings中配置可以访问的路径
 "cors": {
  "default": "http://localhost:0000,http://localhost:1111"
},
在Startup中ConfigureServices下配置
           var urls = Configuration.GetSection("cors:default").Value.Split(',');
services.AddCors(options =>
{
options.AddPolicy("AllowOrigins", builder =>
{
builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
});
});

在Configure中使用

app.UseCors("AllowOrigins");
(2)web API
在Web.config中配置:
        <add key="allowOrigins" value="http://localhost:0000,http://localhost:1111"/>
<add key="allowHeaders" value="*"/>
<add key="allowMethods" value="*"/>
  在WebApiConfig中配置:
    //跨域配置
    var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"];
    var allowHeaders = ConfigurationManager.AppSettings["cors_allowHeaders"];
    var allowMethods = ConfigurationManager.AppSettings["cors_allowMethods"];
    var globalCors = new EnableCorsAttribute(allowOrigins, allowHeaders, allowMethods);
    config.EnableCors(globalCors);
             
    // Web API 路由
    config.MapHttpAttributeRoutes();     config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );