[英]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.