簡體   English   中英

客戶端 Blazor 對 GetRequest 使用 SendAsync 對 API 請求使用 CORS

[英]Client-side Blazor using SendAsync for a GetRequest with CORS for an API request

在設置我的 Blazor 客戶端 API 客戶端以發出請求時,我遇到了 CORS 的一些問題。 我想我找到了解決方案,但解決方案也引發了錯誤。

主要錯誤是:“WASM:System.Net.Http.HttpRequestException:TypeError:無法在'Window'上執行'fetch':提供的值'2'不是RequestCredentials類型的有效枚舉值。”

代碼是

        string link = API_RequestLoginTokenEndPoint;

        Http.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
        Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "basic:testuser:testpassword");

        var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), link);

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

        var response = await Http.SendAsync(requestMessage);
        var responseStatusCode = response.StatusCode;
        var responseBody = await response.Content.ReadAsStringAsync();

        output = responseBody + " " + responseStatusCode;

我還嘗試將請求消息更改為: var requestMessage = new HttpRequestMessage(HttpMethod.Get, link);

如果這是 ENUM 所指的錯誤。 在 Startup ConfigureServices 我嘗試添加: WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;

I am using Blazor preview 9. I also tried adding some CORS code to my PHP script on the API route that should accept all origins, but the last question I posted I was told to use this method to fix the CORS problem, which now gives我一個新的錯誤。

我做錯了什么還是我錯過了什么? 瀏覽器中的錯誤通常指向帶有異步請求的行: var response = await Http.SendAsync(requestMessage);

這是一個尚未修復的錯誤。 改用這個:

requestMessage.Properties[WebAssemblyHttpMessageHandler.FetchArgs] = new
        {
            credentials = "include"
        };

我遇到了類似的問題,無法解決飛行前的活動。

我可以通過注釋掉 HTTP 重定向中間件來解決這個問題

上下文:Blazor 客戶端調用 asp.net.core api 在不同的 Z572D4E421E5E6B9BC11D815E8

不確定這是否是一個好的解決方案,但我覺得在這個令人沮喪的問題上花了 1 周后我需要提及這一點。 希望它可以幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM