张国伟 发表于 2024-6-30 00:43:06

C#进阶-ASP.NET的WebService跨域CORS题目办理方案

在现代的Web应用程序开发中,跨域资源共享(Cross-Origin Resource Sharing, CORS)题目是开发者常常遇到的一个挑衅。特别是当前端和后端服务摆设在不同的域名或端口时,CORS题目就会显得尤为突出。在这篇博客中,我们将深入探讨如何在 .NET WebService 中办理CORS题目,资助开发者顺利实现跨域请求。
一、CORS题目描述

在Web应用中,欣赏器安全机制通常会克制来自不同域的请求,这被称为“同源策略”。同源策略允许同一来源(协议、主机和端口类似)的资源相互访问,但会克制不同来源的资源访问。这种机制虽然提高了安全性,但在现实开发中,前端和后端通常会摆设在不同的服务器上,这就引发了CORS题目。
举个例子,当你试图从 http://frontend.com 发送一个请求到 http://api.backend.com 时,欣赏器会拦截这个请求并抛出一个CORS错误:
Access to XMLHttpRequest at 'http://api.backend.com/resource' from origin 'http://frontend.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
对于 .NET WebService ,如果前端应用尝试从另一个域名访问服务,而服务端没有适当的CORS策略,那么欣赏器会克制这些请求并表现该跨域错误。
二、CORS题目代码示例

为了更好地明白CORS题目及其办理方案,让我们先创建一个简单的前后端交互的.NET WebService示例。
1. 后端WebService接口代码

首先,创建一个新的 .NET Framework 项目。你可以利用 Visual Studio 或者命令行工具(如 dotnet CLI )来创建项目。在项目中,我们定义一个 .asmx 文件,并在 .asmx.cs 文件里创建一个接口。
https://img-blog.csdnimg.cn/direct/3eaff69cf1454bb2a750d8da0f1a78f2.png
https://img-blog.csdnimg.cn/direct/e29d27c08c254e57ac677be2234840a9.png
接口代码如下:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.Services;

namespace TestProject
{
   
   
   
   
    public class Test : WebService
    {

      
      public void GetJsonData()
      {
            string json = "{\"MapPoints\":[{\"Coordinates\":[\"118.87220827635\",\"34.885061248714\"],\"Speed\":\"45.7\",\"Time\":\"2024-05-13T13:02:09\"}]}";
            HttpContext.Current.Response.ContentType = "application/json";
            HttpContext.Current.Response.Write(json);
      }
    }
}
这个控制器有一个GET方法,当请求 http://localhost:80/Test.asmx/GetJsonData 时,它会返回一个串JSON数据。
这里我们可以用 Postman 测试代码,精确返回结果,则验证后端接口代码没有题目。
https://img-blog.csdnimg.cn/direct/94ddcc2978ee48659329fef15779d441.png
2. 前端接口请求代码

这里我利用的前端访问接口的JavaScript代码是基于 axios 实现的。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS Test</title>
</head>

<body>
    <h1>CORS Test</h1>
    <button id="fetchDataButton">Fetch Data</button>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <script>
      document.getElementById('fetchDataButton').addEventListener('click', function () {
            getCarLocation();
      });

      function getCarLocation() {
            axios.get('http://localhost:80/Test.asmx/GetJsonData')
                .then(function (response) {
                  console.log('Success:', response.data);
                })
                .catch(function (error) {
                  console.error('Error:', error);
                });
      }
    </script>
</body>

</html>
页面效果图如下:
https://img-blog.csdnimg.cn/direct/448255bad0224bff8f8a9070382ddca4.png
当点击 Fetch Data 按钮时,页面会访问 http://localhost:80/Test.asmx/GetJsonData 接口,并输出返回值到F12控制台日记里。
此时,如果我们不配置CORS,那么请求会被拦截,并报错:
Access to XMLHttpRequest at 'http://localhost:80/Test.asmx/GetJsonData' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
三、CORS配置具体步骤

为了让我们的 WebService 支持跨域请求,我们须要在项目中配置CORS。在 .NET Framework 中,我们可以通过如下步骤来配置CORS。
1. 配置Global.asax全局请求头参数

创建或打开项目的 Global.asax 文件,找到或添加 Application_BeginRequest() 方法,添加响应头参数,其中 <"Access-Control-Allow-Origin", "*"> 这个响应头是最紧张的。

namespace TestProject
{
    public class Global : System.Web.HttpApplication
    {
      protected void Application_BeginRequest()
      {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "86400");
                HttpContext.Current.Response.StatusCode = 204;
                HttpContext.Current.Response.End();
            }
      }
    }
}
要非常注意的是,每个请求头参数只能添加一次,如果重复添加,依然会访问报错,可以排查一下 web.config 文件或者专门的路由模块有没有已经添加,或者再每次添加之前判定当前请求头是否已经存在,如果存在删除在添加。
2. 创建自定义HTTP模块并注册

在 .NET Framework 中,通过自定义 HTTP 模块修改 HTTP 响应头,可以协助处理跨域题目。
我们右键办理方案,新建项目,创建 ​​CustomHttpModules​​ 模块。
https://img-blog.csdnimg.cn/direct/58f0bf8931834e03940f1809c51a012a.png
https://img-blog.csdnimg.cn/direct/834c0cc639d0407fbc71f5df436951a9.png
模块内创建 HeaderFilterHttpModule.cs 文件。
https://img-blog.csdnimg.cn/direct/2386b698b0f34b74be16383787483d48.png
代码如下 :
using System;
using System.Web;

namespace CustomHttpModules
{
    public class HeaderFilterHttpModule : IHttpModule
    {
      public void Init(HttpApplication context)
      {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
      }

      public void Dispose()
      { }

      void OnPreSendRequestHeaders(object sender, EventArgs e)
      {
            try
            {
                HttpApplication app = sender as HttpApplication;
                if (app != null && app.Context != null && app.Context.Response != null)
                {
                  var headers = app.Context.Response.Headers;
                  if (headers != null)
                  {
                        headers.Remove("Server");
                        headers.Remove("X-AspNet-Version");
                        headers.Remove("X-AspNetMvc-Version");
                        headers.Remove("X-Frame-Options");
                        headers.Remove("X-Powered-By");
                        // 添加CORS相关的头信息
                        headers.Add("Access-Control-Allow-Origin", "*");
                        headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                        headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
                  }
                }
            }
            catch (Exception ex)
            {
                // 记录异常
            }
      }
    }
}

创建完成后,我们到主项目注册这个自定义的 HTTP 模块。
先给主项目添加引用:
右键主项目,添加新模块到引用。
https://img-blog.csdnimg.cn/direct/9c0db41e3d6c40538ac27113bce68a6c.png
然后,打开 web.config 文件,找到 <configuration> 下的 <system.webServer> 标签,引入我们刚刚创建好的 HeaderFilterHttpModule 模块。
<configuration>
<system.webServer>
    <modules>
      <add name="HeaderFilterHttpModule" type="CustomHttpModules.HeaderFilterHttpModule" />
    </modules>
</system.webServer>
</configuration>
3. 测试增加CORS配置后的代码

添加上述有关CORS的配置后,我们重新启动 .NET Framework 项目,通过测试页面点击 Fetch Data 按钮,给 http://localhost:80/Test.asmx/GetJsonData 接口发送请求。
可以看到我们得到了精确的返回值。
{
    "MapPoints": [
      {
            "Coordinates": [
                "118.87220827635",
                "34.885061248714"
            ],
            "Speed": "45.7",
            "Time": "2024-05-13T13:02:09"
      }
    ]
}
.NET WebService 跨域CORS题目完美办理。
四、CORS题目办理总结

通过配置 global.asax 全局文件,创建和注册自定义 HTTP 模块,我们乐成地办理了 .NET WebService 中的 CORS 题目。这种方法的关键在于拦截和修改 HTTP 响应头,添加须要的 CORS 头信息。总结如下:

[*]修改Global.asax文件:修改 Application_BeginRequest 方法,修改全局请求头参数。
[*]创建自定义 HTTP 模块:实现 IHttpModule 接口,并在 PreSendRequestHeaders 变乱中添加或移除 HTTP 头信息。
[*]注册 HTTP 模块:在 Web.config 文件中注册自定义的 HTTP 模块。
[*]测试能否跨域:通过前端发送跨域请求来验证 CORS 配置是否精确。
通过这些步骤,开发者可以有用地办理跨域资源共享题目,确保前后端服务的顺畅通讯。在现实开发中,根据具体项目的需求,CORS 配置可能会有所不同,但核心思想和步骤是类似的。希望这篇博客能为你办理 CORS 题目提供有代价的资助。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: C#进阶-ASP.NET的WebService跨域CORS题目办理方案