【问题标题】:How to make CORS API call from Blazor client app with authentication using AutoRest Client?如何使用 AutoRest 客户端通过身份验证从 Blazor 客户端应用程序进行 CORS API 调用?
【发布时间】:2019-12-10 12:15:03
【问题描述】:

我正在尝试从 Blazor 客户端应用程序调用 Web API。当我使用纯 Javascript 调用 API 时,API 发送所需的 CORS 标头并且工作正常。

API 需要在调用时包含 Auth cookie,因此我可以使用 JavaScript 调用:

fetch(uri, { credentials: 'include' })
        .then(response => response.json())
        .then(data => { console.log(data) })
        .catch(error => console.log('Failed'));

现在,我正尝试在 Blazor 上做同样的事情。我在文档上遇到了this section,上面写着:

requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
    { 
        credentials = FetchCredentialsOption.Include
    }; 

当我现在拨打电话时,它会失败并出现以下异常:

WASM:System.Net.Http.HttpRequestException:TypeError:无法在“Window”上执行“fetch”:提供的值“2”不是 RequestCredentials 类型的有效枚举值。

我注意到在 Statrup.cs 上添加以下内容允许我调用包括凭据 (here) 在内的 API:

if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
        {
            WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;
        }

现在,我想使用 AutoRest 生成的 API 客户端调用 API,这样我就可以重用现有的客户端并节省大量时间。如上所述设置DefaultCredentials 不起作用并显示以下异常:

WASM:Microsoft.Rest.HttpOperationException:操作返回无效状态代码“InternalServerError”

如上设置requestMessage.Properties,说

提供的值“2”不是 RequestCredentials` 类型的有效枚举值。

我已经使用 this technique 从 Blazor 注入 HttpClient

【问题讨论】:

  • 我意识到我的 HttpClient 初始化错误。 Fiddler 拯救了这一天!

标签: asp.net-core cors blazor


【解决方案1】:

这不是真正的答案...我只需要空间

设置 requestMessage.Properties 如上所述,提供的 值“2”不是 RequestCredentials 类型的有效枚举值

如果是这样,我建议的另一种方法有什么问题,我猜它是有效的。

顺便说一句,

提供的值“2”不是类型的有效枚举值 请求凭据

与 Blazor 无关,对吧? Blazor 中没有这种类型 (RequestCredentials)。也许您的代码(无论它是什么)获取 FetchCredentialsOption.Include 的数值,而不是它的 Enum 字符串

考虑实例化一个 HttpRequestMessage 对象,并根据您的要求进行配置。

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2012-11-02
    • 2020-12-26
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-30
    相关资源
    最近更新 更多