• .NET Core如何启用CORS以实现跨域访问
  • 发布于 2个月前
  • 174 热度
    0 评论
浏览器的安全阻止一个域的本地页面请求另外不同域的本地页面,这个限制叫同源策略,这个安全特性用来阻止恶意站点从别的网站读取数据。

例如假如我有一个页面叫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 。


一.CORS如何工作
站点一旦启用了CORS,Access-Control-Allow-Origin会被添加到请求的头部,请求头部将被自动设置跨域请求,因此,当一个页请求到另外一个服务器或者域名的资源,服务器的响应Access-Control-Allow-Origin值被设置。通常,这个值为*,这意味着服务器共享请求资源针对互联网上的每个域名,有时候,这个header的值将被设置为特定域名(或者域名列表),这意味着服务将共享资源仅仅针对特定域名(域列表)。

二.在ASP.NET Core中启用CORS
在启动项中添加如下代码:
builder.Services.AddCors();
注意我们添加代码行使用可选AllowAnyOrigin允许每一个域能够CORS请求:
app.UseCors(builder =>
{
    // 堆代码 duidaima.com
    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();
});
三.在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: "{controller=Home}/{action=Index}/{id?}");
app.Run();
将策略名字传递到UseCors()方法:现在将CORS策略应用到每个action或者controller
3.1 每个Action
指定CORS策略针对特定的action,在action上添加[EnableCors]特性并指定策略名称:
[EnableCors("MyPolicy")]
public IEnumerable<string> 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";
}

用户评论