首页 > 解决方案 > 从 Blazor 发出 CORS 请求时如何包含凭据?

问题描述

在 Blazor 客户端应用程序上,jQuery ajaxWithCredentials或 JavaScript的等价物是什么credentials: 'include'

使用 Javascript 我可以说:

fetch('https://www.example.com/api/test', {
   credentials: 'include'
});

其中包括 auth cookie,同时发出请求,服务器响应 200。我正在尝试使用 Blazor 编写相同的HttpClient.

标签: asp.net-corecorsblazor

解决方案


在您的 Startup.Configure 方法中,您可以将 WebAssemblyHttpMessageHandler.DefaultCredentials 设置为出站 HTTP 请求的“凭据”选项的所需值,如下所示:

public void Configure(IComponentsApplicationBuilder app)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
            {

                WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;
            }

            app.AddComponent<App>("app");
        }

参考资料: https ://github.com/aspnet/AspNetCore/blob/c39fbb8f12002f61df6c093b0c11e6bd585ee202/src/Components/Blazor/Blazor/src/Http/WebAssemblyHttpMessageHandler.cs

https://github.com/aspnet/AspNetCore/blob/5a70f5312fb57fc3788e5af56a99e7b43761e195/src/Components/Blazor/Blazor/src/Http/FetchCredentialsOption.cs

https://github.com/aspnet/AspNetCore/blob/d18a033b1ee6d923a72d440718c5d496b57c2ffc/src/Components/test/testassets/BasicTestApp/Startup.cs

希望这可以帮助...


推荐阅读