我正在開發我的第一個 Blazor 應用程式。我嘗試請求一個休息 API 來獲取資料。
我已經在其他應用程式中使用了這個 API,所以我確信它可以正常作業。
我的 HTTP 請求被我的 API 拒絕:API 沒有檢測到我要添加的標頭,因此請求被拒絕。
在我的 API 中,我檢查我的用戶和密碼:
protected override bool CheckAccessCore(OperationContext operationContext)
{
string AuthHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if(!string.IsNullOrWhiteSpace(AuthHeader))
{
return CheckCredentials(AuthHeader);
}
return false;
}
此代碼適用于其他應用程式。
在我的 Blazor 專案中,我這樣呼叫我的 API:
在 Program.cs 中,我宣告了我的 Httpclient :
builder.Services.AddScoped(sp => new HttpClient{BaseAddress = new Uri("https://localhost:44346/MyServiceRest.svc")});
builder.Services.AddScoped<ProjectModel.ClsMetierService>();
我在我的 ClsMetierService 類中添加了一個建構式來獲取我的范圍 httpclient :
HttpClient httpClient;
public ClsMetierService(HttpClient _httpClient)
{
httpClient = _httpClient;
在我的方法中,我呼叫我的 httpclient 并設定我的標頭:
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("GET"),
RequestUri = new Uri(urlStream)
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Authorization", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("Admin:Password")));
requestMessage.Content.Headers.TryAddWithoutValidation("Test", "Value");
var response = await httpClient.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
JsonResult = await response.Content.ReadAsStringAsync();
return JsonResult;
如果我CheckAccessCore在 API 中設定斷點,則該AuthHeader變數為空。我檢查了incomingrequest.Headers,我得到了 14 個標頭的串列,它們都不是“授權”或“測驗”,就好像我的標頭沒有添加到我的請求中一樣:

我認為問題出在TryAddWithoutValidation方法上,但我的第二個標題“測驗”也不存在。
我通常使用 HttpWebRequest 并以這種方式:
httpReq.Headers.Add("Authorization", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("login:password")));
但是使用 Blazor WebAssembly 我得到這個錯誤: System.Net.Request is not supported on this platform
如何為我的HttpClient請求設定自定義標頭?
uj5u.com熱心網友回復:
您應該參考https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-5.0&pivots=webassembly
從 Blazor WebAssembly 應用程式發出 Http 請求的正確方法是注入一個HttpClient旨在在 WASM 中作業的HttpClient.
要添加標頭,請參閱部分(“.. with Fetch API request options”]( https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore -5.0&pivots=webassembly#httpclient-and-httprequestmessage-with-fetch-api-request-options-1 )
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token.Value);
requestMessage.Content.Headers.TryAddWithoutValidation(
"x-custom-header", "value");
uj5u.com熱心網友回復:
沒關系,Blazor WASM 太有限,不能滿足我的需要,我必須重寫我現有的 API……我在 blazor 服務器上重新制作了我的應用程式,它作業正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341008.html
標籤:西装外套 http客户端 休息 blazor-webassembly
上一篇:格式化來自API的資料
