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

注:下载本文的完整代码示例请访问 > How to enable CORS(Cross-origin resource sharing) in ASP.NET Corehtml

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

CORS(Cross-origin resource sharing)是一个W3C标准,翻译过来就是 "跨域资源共享",它主要是解决Ajax跨域限制的问题。
CORS须要浏览器和服务器支持,如今全部现代浏览器都支持这一特性。注:IE10及以上
只要浏览器支持,其实CORS全部的配置都是在服务端进行的,而前端的操做浏览器会自动完成。前端

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

前期准备

建立项目

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

ajax

配置服务端

注:添加下面的代码时IDE会提示代码错误,这是由于尚未引用对应的包,进入报错的这一行,点击灯泡,加载对应的包就能够了。

(图文无关)c#

  • 打开Startup.cs
    • 在ConfigureServices中添加以下代码:
    services.AddCors();
    • 在Configure方法中添加以下代码:
    app.UseCors(builder => builder.WithOrigins("http://localhost"));

    完整的代码应该是这样:
    ```
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddCors();
    }windows

    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!");
    });
    }
    ```api

来让咱们运行一下:
输出结果很简单,你会在浏览器上看到一个Hello World!跨域

浏览器端

既然是跨域,那咱们就须要用两个域名,上面咱们已经有了一个,相似于这样的:http://localhost:1661/
接下来咱们来用过IIS来搭建另一个。浏览器

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

首先咱们新建一个文件夹,并将IIS默认的localhost网站的根目录指向该文件夹。
在该文件夹中添加一个文件index.html。
内容应该是这个样子:

<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请求跨域,会自动添加一些附加的头信息并请求到目标服务器(会带有本域的域名),目标服务器则检测该域名是否在容许跨域的域名之列,若是有则返回请求结果,不然失败。
具体的原理能够看看这篇博客:跨域资源共享 CORS 详解

分组策略以及MVC

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

  • Startup.cs
    • ConfigureServices中
    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中
    app.UseMvc();

    完整的代码应该是这样:
    ```
    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
    其中的内容应该是这样:
    ```
    //[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,内容应为:
<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, 则请求会被拦截。

注:下载本文的完整代码示例请访问 > How to enable CORS(Cross-origin resource sharing) in ASP.NET Core

相关文章
相关标签/搜索