萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

ASP.NET 後端跨域請求處理:HttpModule 實現反向代理

場景

前端項目部署在 localhost:8080,後端 API 在 localhost:89。瀏覽器同源策略阻止直接 AJAX 請求。解決方案:前端請求同源地址(如 /Server/api/xxx),後端 HttpModule 攔截並轉發至真實 API 服務器。

HttpModule 實現

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();
        }
    }
}

Web.config 註冊

<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 運行時新專案/遷移專案

CORS 快速配置對比

// ASP.NET Core Middleware (Startup.cs)
app.UseCors(builder => builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());

總結

HttpModule 反向代理是 ASP.NET Framework 時代解決跨域的經典方案,通過 BeginRequest 早期攔截、路徑重寫、請求轉發、響應透傳實現。新專案強烈建議採用 CORS 標頭 或 Nginx 反向代理,架構更清晰、維護成本更低、符合現代前後端分離最佳實踐。

copyright © 萬盛學電腦網 all rights reserved