Asp.net core 跨域设置
验证环境:
dotnet core 2.1/Asp.net core2.1
一、作用域在中间件层
配置的方式是在startup.cs文件Configure(IApplicationBuilder app, IHostingEnvironment env)方法中增加跨域配置。官方示例:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseCors(builder => builder.WithOrigins("http://example.com")); app.UseMvc();
}
使用app.UseCors(builder =>builder.WithOrigins("http://example.com"));
"http://example.com"为要允许跨域的地址,WithOrigins可以支持多个地址。
官方说明app.UseCors方法设置须在app.UserMvc 或者app.Run 前。
二、跨域策略定义
可在startup.cs文件ConfigureServices(IServiceCollection services)方法中定义策略,支持定义多个策略。官方示例:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; namespace CorsExample4
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
// BEGIN01
options.AddPolicy("AllowSpecificOrigins",
builder =>
{
builder.WithOrigins("http://example.com", "http://www.contoso.com");
});
// END01 // BEGIN02
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin();
});
// END02 // BEGIN03
options.AddPolicy("AllowSpecificMethods",
builder =>
{
builder.WithOrigins("http://example.com")
.WithMethods("GET", "POST", "HEAD");
});
// END03 // BEGIN04
options.AddPolicy("AllowAllMethods",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyMethod();
});
// END04 // BEGIN05
options.AddPolicy("AllowHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.WithHeaders("accept", "content-type", "origin", "x-custom-header");
});
// END05 // BEGIN06
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyHeader();
});
// END06 // BEGIN07
options.AddPolicy("ExposeResponseHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.WithExposedHeaders("x-custom-header");
});
// END07 // BEGIN08
options.AddPolicy("AllowCredentials",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowCredentials();
});
// END08 // BEGIN09
options.AddPolicy("SetPreflightExpiration",
builder =>
{
builder.WithOrigins("http://example.com")
.SetPreflightMaxAge(TimeSpan.FromSeconds());
});
// END09
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(); if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseCors("AllowSpecificOrigins");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
使用app.UseCors("AllowSpecificOrigins");调用具体的跨域策略,“AllowSpecificOrigins”为策略名,跨域作用域在中间层上。
策略定义和使用方法详见官方的参考文章(本文最后给出地址)。
三、作用域在MVC层
在使用MVC时,官方给出的3种设置方式,分别是Action前设置、Controller前设置、全局性设置。
- Action
在Action 方法前增加标记EnableCors(策略名称).官方示例
[HttpGet]
[EnableCors("AllowHeaders")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
EnableCors 在Microsoft.AspNetCore.Cors命名空间下。"AllowHeaders"为策略名称。
- Controller
在Controller前增加标记EnableCors(策略名称).官方示例
[EnableCors("AllowSpecificOrigin")]
public class ValuesController : Controller
- MVC全局(Globally)
官方说明是通过“CorsAuthorizationFilterFactory”过滤器方式给所有Controller增加跨域设置。官方示例:
using Microsoft.AspNetCore.Mvc.Cors.Internal; ... public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
//...策略设置...
}); services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllMethods"));
});
}
CorsAuthorizationFilterFactory在命名空间Microsoft.AspNetCore.Mvc.Cors.Internal下。“AllowAllMethods”为策略名称。
- 禁用跨域
官方说明可以使用标记“DisableCors”设置Action或Controller跨域设置不起作用。官方示例:
[HttpGet("{id}")]
[DisableCors]
public string Get(int id)
{
return "value";
}
DisableCors在命名空间Microsoft.AspNetCore.Cors下。
四、整体作用范围
作用范围,Middleware>Globally>Controller>Action。
生效优先顺序是Action,Controller,Globally,Middleware。即Action定义了跨域优先Controller生效,Controller优先Globally,Globally优先Middleware。
如果定义了跨域不生效,就要检查Action 和Controller 及Controller基类是否定义了其他的跨域设置。
官方参考文章:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1
Asp.net core 跨域设置的更多相关文章
- Asp.net Core 跨域配置
一般情况WebApi都是跨域请求,没有设置跨域一般会报以下错误 No 'Access-Control-Allow-Origin' header is present on the requested ...
- Asp.Net Core跨域配置
在没有设置跨域配置的时候,Ajax请求时会报以下错误 已拦截跨源请求:同源策略禁止读取位于 http://localhost:5000/Home/gettime 的远程资源.(原因:CORS 头缺少 ...
- C# ASP.NET WebApi 跨域设置
概述 前后端分离开发模式,一定会遇到跨域的问题.这里收集了2种 C# Asp.Net webapi 相关的跨域解决方案,方便后续查找参考. 2021/10/28 更新: 有更加简单高效的方式推荐< ...
- Asp.Net WebApi 跨域设置
跨越问题主要发生在客户端ajax请求时,为了安全设置,默认webapi是不允许ajax跨越请求的,不过有方法设置让支持跨越,我说说最常见的两种方法 一.jquery jsonp 缺点:JSONP也有局 ...
- .net core跨域设置
services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder. ...
- C# ASP.NET MVC/WebApi 或者 ASP.NET CORE 最简单高效的跨域设置
概述 前面写了一篇:<C# ASP.NET WebApi 跨域设置>的文章,主要针对 ASP.NET WebApi 项目. 今天遇到 ASP.NET MVC 项目也需要设置跨域,否则浏览器 ...
- 连表查询都用Left Join吧 以Windows服务方式运行.NET Core程序 HTTP和HTTPS的区别 ASP.NET SignalR介绍 asp.net—WebApi跨域 asp.net—自定义轻量级ORM C#之23中设计模式
连表查询都用Left Join吧 最近看同事的代码,SQL连表查询的时候很多时候用的是Inner Join,而我觉得对我们的业务而言,99.9%都应该使用Left Join(还有0.1%我不知道在 ...
- ASP.NET WebAPI2复杂请求跨域设置
ASP.Net Core的跨域设置比较简单 官方都整合了 具体的参见微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/security/cor ...
- .net core 下的跨域设置
1.CORS中间件处理跨源请求.以下代码为具有指定源的整个应用程序启用CORS: public void Configure(IApplicationBuilder app, IHostingEnvi ...
随机推荐
- Js学习(6) 标准库-Array对象
Array是Js的原生对象,同时也是一个构造函数,可以用它生成新的数组 用不用new结果都一样 var arr = new Array(2); // 等同于 var arr = Array(2); 但 ...
- tomcat7闪退
问题是我昨天运行的好好的,今天加了些代码,tomcat7就会启动闪退.我把conf/server.xml中的<Context />去掉,tomcat又能正常启动! 那么问题出在哪里呢? 我 ...
- Spark官方文档翻译(一)~Overview
Spark官方文档翻译,有问题请及时指正,谢谢. Overview页 http://spark.apache.org/docs/latest/index.html Spark概述 Apache Spa ...
- Linux驱动之异常处理体系结构简析
异常的概念在单片机中也接触过,它的意思是让CPU可以暂停当前的事情,跳到异常处理程序去执行.以前写单片机裸机程序属于前后台程序,前台指的就是mian函数里的while(1)大循环,后台指的就是产生异常 ...
- Python列表详解
#列表:增,删,改,查.names=['N0','N1','N2',['EX1','EX2'],'N3'] '''#------------------------------------------ ...
- How to configure Samba Server share on Debian 9 Stretch Linux
Lubos Rendek Debian 13 June 2017 Contents 1. Objective 2. Operating System and Software Versions 3. ...
- flask更改已有的response
今天遇到个问题,需要更改返回的response,但框架已经生成了一个response,所以需要直接更改. 试着找了找解决办法,最终解决方式如下: #下文中payload的类型是 # class Res ...
- 2019.02.17 spoj Query on a tree V(链分治)
传送门 题意简述: 给你一棵nnn个黑白点的树,初始全是黑点. 现在支持给一个点换颜色或者求整颗树中离某个点最近的白点跟这个点的距离. 思路: 考虑链分治维护答案,每个链顶用一个堆来维护答案,然后对于 ...
- MFC头文件
AFX.H struct CRuntimeClass; // object type information class CObject; // the root of all objects cla ...
- vue使用矢量图
1.在阿里巴巴矢量图标下载下来 2.放到static下 3.main.js下 import '../static/iconfont/iconfont.css' 4.调用<i class=&quo ...