[英]Handle CORS HTTP Options Preflight Request in a .NET 6 Minimal API?
似乎無法弄清楚如何在 .NET 6 中以最小的 API 處理 CORS 選項(預檢)請求。
雖然有用於路由的 MapGet 和 MapPost,但沒有專門的 MapOptions。 我們確實有 MapMethods,我試圖用它來強制對選項請求做出 200 響應,如下所示,但這似乎打破了 Swagger:
app.MapGet("/HelloWorld", () => "Hello World!");
app.MapMethods("/HelloWorld", new[] {"OPTIONS", "HEAD"},
() => processOptions);
app.Run();
IResult processOptions()
{
return Results.Ok();
}
文檔提到在基於 API 的 controller 中執行此操作,如下所示,但我不確定如何將其轉換為最小的 api
在 .NET Framework 4.7 中,我將添加以下內容以允許對選項請求做出 200 ok 響應:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Context.Request.HttpMethod == "OPTIONS")
{
Response.End();
}
}
(Response.End 方法中的注釋說它做了以下事情):
// Summary:
// Sends all currently buffered output to the client, stops execution of the page,
// and raises the System.Web.HttpApplication.EndRequest event.
//
// Exceptions:
// T:System.Threading.ThreadAbortException:
// The call to System.Web.HttpResponse.End has terminated the current request
使用 Application_AuthenticateRequest 使 Options 請求在 .Net Framework 4.7 中工作也讓我想到也許正在發生的事情是我需要以某種方式對用戶進行身份驗證,這根本不是 CORS 選項問題,這是一個單獨的問題。 .
這個問題:在 .NET 6+ 中處理選項請求的正確方法是什么?
在我看來,您可以編寫自定義中間件來滿足您的要求。
如果你想匹配選項和頭部請求並在你的應用程序中返回一些東西,你可以在中間件下面編寫並將它放在你的應用程序的開頭。
然后所有的option和head request都會把200返回給client。
更多詳細信息,您可以參考以下代碼:
app.Use(async (context, next) =>
{
var methodvalue = context.Request.Method;
if (!string.IsNullOrEmpty(methodvalue))
{
if (methodvalue == HttpMethods.Options || methodvalue == HttpMethods.Head)
{
await context.Response.WriteAsync("Option Request");
}
else
{
await next();
}
}
});
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.