gpt4 book ai didi

谈谈如何在ASP.NET Core中实现CORS跨域

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 24 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章谈谈如何在ASP.NET Core中实现CORS跨域由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

CORS(Cross-origin resource sharing)是一个W3C标准,翻译过来就是 "跨域资源共享",它主要是解决Ajax跨域限制的问题.

CORS需要浏览器和服务器支持,现在所有现代浏览器都支持这一特性。注:IE10及以上 。

只要浏览器支持,其实CORS所有的配置都是在服务端进行的,而前端的操作浏览器会自动完成.

在本例中,将演示如何再ASP.NET Core中实现CORS跨域.

前期准备 。

你需要windows系统.

你需要安装IIS.

推荐使用VS2015 Update3或更新的版本来完成本例 。

需要安装.NET Core的开发环境 。

创建项目 。

在VS中新建项目,项目类型选择ASP.NET Core Web Application(.NET Core),输入项目名称为:CSASPNETCoreCORS,Template选择Empty. 。

谈谈如何在ASP.NET Core中实现CORS跨域

谈谈如何在ASP.NET Core中实现CORS跨域

配置服务端 。

注:添加下面的代码时IDE会提示代码错误,这是因为还没有引用对应的包,进入报错的这一行,点击灯泡,加载对应的包就可以了.

(图文无关) 。

打开Startup.cs 。

在ConfigureServices中添加如下代码:

?
1
services.AddCors();

在Configure方法中添加如下代码:

?
1
app.UseCors(builder => builder.WithOrigins(<a href= "http://localhost/" >http://localhost</a>));

完整的代码应该是这样:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public void ConfigureServices(IServiceCollection services)
{
   services.AddCors();
}
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   app.UseCors(builder => builder.WithOrigins( "http://localhost" ));
   app.Run(async (context) =>
   {
     await context.Response.WriteAsync( "Hello World!" );
   });
}

来让我们运行一下:

输出结果很简单,你会在浏览器上看到一个Hello World.

浏览器端 。

既然是跨域,那我们就需要用两个域名,上面我们已经有了一个,类似于这样的:http://localhost:1661/ 。

接下来我们来用过IIS来搭建另外一个.

为了文章的简洁,这里假设你已知道如何在IIS上搭建一个网站,如有疑问,网上一堆答案.

首先我们新建一个文件夹,并将IIS默认的localhost网站的根目录指向该文件夹.

在该文件夹中添加一个文件index.html.

内容应该是这个样子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
< html xmlns = "http://www.w3.org/1999/xhtml" >
< head >
   < title ></ title >
   < script src = "https://code.jquery.com/jquery-3.1.1.min.js" ></ script >
</ head >
< body >
   < script >
     $.get("http://localhost:1661/", {}, function (data) {
       alert(data);
     }, "text");
   </ script >
</ body >
</ html >

注:请求的地址应为你上个项目的调试地址,撰写此文时我项目的调试地址为http://localhost:1661/,具体以自己的情况为准.

浏览localhost这个网站,js会跨域请求另外一个域名的地址,并弹出返回值.

在发起ajax请求时,浏览器一旦发现Ajax请求跨域,会自动添加一些附加的头信息并请求到目标服务器(会带有本域的域名),目标服务器则检测该域名是否在允许跨域的域名之列,如果有则返回请求结果,否则失败.

分组策略以及MVC 。

上例仅仅是一个基本的配置方法,接下来将演示更高级一点的方式,下面将演示在分组策略以及与MVC的整合。 Startup.cs •ConfigureServices中 。

?
1
2
3
4
5
6
7
8
9
10
11
services.AddCors(options =>
{
   options.AddPolicy( "AllowSpecificOrigin" , builder =>
   {
     builder.WithOrigins( "http://localhost" , "https://www.microsoft.com" );
   });
   options.AddPolicy( "AllowSpecificOrigin1" , builder =>
   {
     builder.WithOrigins( "http://localhost:8080" , "https://www.stackoverflow.com" );
   });
});

services.AddMvc(),

Configure中 。

?
1
app.UseMvc();

完整的代码应该是这样:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(options =>
   {
     options.AddPolicy( "AllowSpecificOrigin" , builder =>
     {
       builder.WithOrigins( "http://localhost" , "https://www.microsoft.com" );
     });
   });
 
   services.AddMvc();
}
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   app.UseMvc();
}

接下来我们来添加Controller 。

在项目中添加一个目录Controllers,并在其中添加一个APIController,命名为HomeAPIController.cs 。

其中的内容应该是这样:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//[EnableCors("AllowSpecificOrigin")]
[Route( "api/[controller]" )]
 
public class HomeAPIController : Controller
{
   [EnableCors( "AllowSpecificOrigin" )]
   [HttpGet]
   public string Get()
   {
     return "this message is from another origin" ;
   }
 
   [DisableCors]
   [HttpPost]
   public string Post()
   {
     return "this method can't cross origin" ;
   }
}

[EnableCors("AllowSpecificOrigin")] 既为在本 controller 或 action 中应用哪个分组策略.

[DisableCors] 则为本controller或action不允许跨域资源请求 。

改造浏览器端html 。

修改localhost网站的index.html,内容应为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
< html xmlns = "http://www.w3.org/1999/xhtml" >
< head >
< title ></ title >
< script src = "https://code.jquery.com/jquery-3.1.1.min.js" ></ script >
</ head >
< body >
< script >
   $.get("http://localhost:1661/API/HomeAPI", {}, function (data) {
     alert(data);
   }, "text");
</ script >
</ body >
</ html >

调试 。

F5调试服务端项目,你会看到一个404页面,因为默认路径上没有页面,不用管它,浏览http://localhost, js会Get请求http://localhost:1661/API/HomeAPI,并弹出返回值,而如果你去Post请求http://localhost:1661/API/HomeAPI, 则请求会被拦截.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.

原文链接:http://www.cnblogs.com/onecodeonescript/p/6121009.html 。

最后此篇关于谈谈如何在ASP.NET Core中实现CORS跨域的文章就讲到这里了,如果你想了解更多关于谈谈如何在ASP.NET Core中实现CORS跨域的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com