商城网站开发 价格,网站设计大概在什么价位,阿里云免费域名领取,上海软件外包公司排名浏览器的安全阻止一个域的本地页面请求另外不同域的本地页面#xff0c;这个限制叫同源策略#xff0c;这个安全特性用来阻止恶意站点从别的网站读取数据
例如假如我有一个页面叫A.html
https://foo.example/A.html
现在页面A.html有一个ajax代码尝试读取B.html的HTML的源…浏览器的安全阻止一个域的本地页面请求另外不同域的本地页面这个限制叫同源策略这个安全特性用来阻止恶意站点从别的网站读取数据
例如假如我有一个页面叫A.html
https://foo.example/A.html
现在页面A.html有一个ajax代码尝试读取B.html的HTML的源代码B页面位于
https://bar.other
B.html位于不同的域由于同源策略限制A.html不能做ajax请求ajax调用将返回错误消息
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
W3C提供了标准来放宽同源策略允许实现跨源资源共享(CORS)如果https://bar.other实现CORS https://foo.example/A.html能够ajax请求并读取B.html
1 CORS如何工作
站点一旦启用了CORSAccess-Control-Allow-Origin会被添加到请求的头部请求头部将被自动设置跨域请求
因此当一个页请求到另外一个服务器或者域名的资源服务器的响应Access-Control-Allow-Origin值被设置
通常这个值为*这意味着服务器共享请求资源针对互联网上的每个域名有时候这个header的值将被设置为特定域名(或者域名列表)这意味着服务将共享资源仅仅针对特定域名(域列表)。
2 在ASP.NET Core中启用CORS
在启动项中添加如下代码
builder.Services.AddCors();
注意我们添加代码行使用可选AllowAnyOrigin允许每一个域能够CORS请求
app.UseCors(builder
{builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
下面描述了各个方法作用
AllowAnyMethod() – 允许所有HTTP方法
AllowAnyHeader() – 允许所有请求头
AllowCredentials() – 服务器必须允许凭据
如果只针对特定的域名启用CORS像http://www.domain.com , 在这种场景下你需要修改代码如下
app.UseCors(builder
{builder.WithOrigins(http://www.domain.com).AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
你也可以指定多个域在下面
app.UseCors(builder
{builder.WithOrigins(new string[] { https://example1.com, https://example2.com }).AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
3 在action或者controller上应用CORS策略
我们能定义一个或者多个CORS策略针对策略添加CORS规则我们将这些CORS规则应用到Controller和Action方法
下面代码定义了用户CORS策略命名为MyPolicy
var builder WebApplication.CreateBuilder(args);
// Adding CORS Policy
builder.Services.AddCors(options
{options.AddPolicy(MyPolicy,builder builder.WithOrigins(https://www.yogihosting.com));
});
// Add services to the container.
builder.Services.AddControllersWithViews();
var app builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{app.UseExceptionHandler(/Home/Error);// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// Shows UseCors with named policy.
app.UseCors(MyPolicy);
app.UseAuthorization();
app.MapControllerRoute(name: default,pattern: {controllerHome}/{actionIndex}/{id?});
app.Run();
将策略名字传递到UseCors()方法现在将CORS策略应用到每个action或者controller
3.1 每个Action
指定CORS策略针对特定的action在action上添加[EnableCors]特性并指定策略名称
[EnableCors(MyPolicy)]
public IEnumerablestring Get()
{return new string[] { value1, value2 };
}
3.2 每个Controller
[EnableCors(MyPolicy)]
public class HomeController : Controller
在Controller和action上禁用CORS使用[DisableCors]特性
[DisableCors]
public string Get(int id)
{return value;
}
源代码地址
https://github.com/bingbing-gui/Asp.Net-Core-Skill/tree/master/Fundamentals/AspNetCore.GlobalizationLocalization/AspNetCore.GlobalLocalResFiles