前端項目部署在 localhost:8080,後端 API 在 localhost:89。瀏覽器同源策略阻止直接 AJAX 請求。解決方案:前端請求同源地址(如 /Server/api/xxx),後端 HttpModule 攔截並轉發至真實 API 服務器。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.SessionState;
namespace GL
{
public class CrossDomainHandler : IHttpModule, IRequiresSessionState
{
public void Dispose() { }
public void Init(HttpApplication context)
{
// 在請求開始階段攔截
context.BeginRequest += Context_PreRequestHandlerExecute;
}
private void Context_PreRequestHandlerExecute(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
var context = app.Context;
// 設置響應編碼
context.Response.AppendHeader("charset", "utf-8");
context.Response.AppendHeader("defaultCharset", "utf-8");
context.Response.ContentType = "text/html; charset=utf-8";
// 獲取相對路徑:~/Server/api/users → /api/users
var relativePath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(2); // 去掉 "~/"
// 只代理以 /Server 開頭的路徑
if (!relativePath.StartsWith("Server", StringComparison.OrdinalIgnoreCase))
return;
// 構建目標 URL
var targetUrl = "https://localhost:89" + relativePath.Substring(relativePath.IndexOf('/'));
// 創建轉發請求
var request = (HttpWebRequest)WebRequest.Create(targetUrl);
request.Method = "POST"; // 統一轉為 POST
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 60000;
// 複製表單數據
var sb = new StringBuilder("a=a&"); // 佔位避免空 body
foreach (string key in context.Request.Form.AllKeys)
{
sb.AppendFormat("{0}={1}&", key, context.Request.Form[key]);
}
string postData = sb.ToString().TrimEnd('&');
// 寫入請求流
using (var reqStream = request.GetRequestStream())
using (var writer = new StreamWriter(reqStream, Encoding.UTF8))
{
writer.Write(postData);
}
// 獲取響應並返回給客戶端
using (var response = (HttpWebResponse)request.GetResponse())
using (var respStream = response.GetResponseStream())
using (var reader = new StreamReader(respStream, Encoding.UTF8))
{
string html = reader.ReadToEnd();
context.Response.Write(html);
}
// 終止後續管道處理
context.Response.End();
}
}
}
<configuration>
<system.webServer>
<modules>
<add name="CrossDomainHandler" type="GL.CrossDomainHandler" />
</modules>
</system.webServer>
</configuration>
| 環節 | 說明 |
|---|---|
| 攔截時機 | BeginRequest 事件,早期介入,避免後續管道處理 |
| 路徑映射 | /Server/xxx → https://localhost:89/xxx |
| 方法統一 | 前端可用 GET/POST,模塊統一轉為 POST 轉發 |
| 數據透傳 | 遍歷 Request.Form 重構表單體 |
| 編碼處理 | 請求/響應均強制 UTF-8 |
| Session 支持 | 實現 IRequiresSessionState 讀寫 Session |
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| HttpModule (本文) | 無侵入業務代碼、IIS 原生、性能好 | 僅限 ASP.NET Framework、配置繁瑣 | 舊專案快速解決跨域 |
| CORS 標頭 | 標準、瀏覽器原生支持、前後端分離友好 | 需後端配置、複雜請求需 Preflight | 現代 Web API 首選 |
| 反向代理 | Nginx/IIS ARR/Apache 代理、透明無感知 | 需運維配置、非代碼控制 | 生產環境標準部署 |
| ASP.NET Core Middleware | 跨平台、管道可控、依賴注入友好 | 需 Core 運行時 | 新專案/遷移專案 |
// ASP.NET Core Middleware (Startup.cs)
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
HttpModule 反向代理是 ASP.NET Framework 時代解決跨域的經典方案,通過 BeginRequest 早期攔截、路徑重寫、請求轉發、響應透傳實現。新專案強烈建議採用 CORS 標頭 或 Nginx 反向代理,架構更清晰、維護成本更低、符合現代前後端分離最佳實踐。