Skip to content

Instantly share code, notes, and snippets.

@flashlin
Created July 1, 2021 14:30
Show Gist options
  • Save flashlin/4b22eecd55ec3cae9d5cd2622b06710d to your computer and use it in GitHub Desktop.
Save flashlin/4b22eecd55ec3cae9d5cd2622b06710d to your computer and use it in GitHub Desktop.
RequestProxy

創建一個新的 API 項目。在項目的 Startup 類的 ConfigureServices 方法中,使用AddCors擴展方法向 CORS 選項添加策略。

services.AddCors(options => { options.AddPolicy( "Open", builder => builder.AllowAnyOrigin().AllowAnyHeader()); });

CorsPolicyBuilder 對像有一組可鏈接的方法,它們為允許的來源、標題和方法設置各種規則。在這裡,我剛剛說過,我將接受任何來源和任何標題。請注意,這僅用於演示目的:接受任何來源並不真正安全,因為它允許任何站點連接到代理。

在 Configure 方法中,使用您剛剛定義的策略的名稱調用 UseCors。

app.UseRouting(); app.UseCors("Open"); app.UseAuthorization();

中間件順序很重要。CORS 設置必須在路由之後和授權之前進行。這就是允許客戶端連接到代理的原因。

接下來,我們需要從客戶端獲取我們允許的請求並將它們傳遞給目標 API。同樣,這些部分已經建成,我們只需要把它們放在一起。

從 NuGet,安裝

Microsoft.AspNetCore.Http.Abstractions和 Microsoft.AspNetCore.Proxy

HTTP Abstractions 程序集添加了使用MapWhen函數分支中間件管道的能力,代理程序集將請求傳遞給目標。

向 Startup 的 Configure 方法添加新的映射規則

app.MapWhen( context => context.Request.Path.StartsWithSegments("/api"), builder => builder.RunProxy(new ProxyOptions { Scheme = "https", Host = "example.com", Port = "80", }) );

謂詞可以檢查請求並決定是否採取分支。任何傳入並滿足條件的請求都將根據代理選項進行重定向。

代理不受 JavaScript 沙箱規則的約束,可以直接發出請求,無需同源策略或飛行前請求。當它得到響應時,它將它傳遞回原始調用者。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment