How to resolve "TypeError: Failed to fetch" error on Blazor?

How to resolve "TypeError: Failed to fetch" error on Blazor?

我正在尝试从我的 Blazor 应用向我的 ASP.NET Core API 发送 HTTP 请求。我到处都有断点。应用程序在 API 控制器 returns 上的操作方法之后立即给出异常。我对 .NET 总体上很熟悉,但是,我无法解读错误消息。

Blazor http 调用:

var response = await _httpClient.GetStreamAsync($"Customer/GetAllCustomers");

ASP.NET 核心 API 控制器动作:

[HttpGet]
[Route("GetAllCustomers")]
public async Task<IEnumerable<Customer>> GetAllCustomersAsync()
{
    return await _service.GetAllCustomersAsync();
}

错误堆栈:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: TypeError: Failed to fetch
WebAssembly.JSException: TypeError: Failed to fetch
  at System.Net.Http.WebAssemblyHttpHandler.doFetch (System.Threading.Tasks.TaskCompletionSource`1[TResult] tcs, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x301ab40 + 0x00a30> in <filename unknown>:0 
  at System.Net.Http.WebAssemblyHttpHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2ff3590 + 0x00174> in <filename unknown>:0 
  at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2ff1e98 + 0x00160> in <filename unknown>:0 
  at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2fc8a98 + 0x00182> in <filename unknown>:0 
  at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) <0x301ff08 + 0x00134> in <filename unknown>:0 
  at System.Net.Http.HttpClient.FinishGetStreamAsync (System.Threading.Tasks.Task`1[TResult] getTask) <0x2ffa720 + 0x000cc> in <filename unknown>:0 
  at WebClient.Services.LectureVideoService.GetAllLectureVideos (Content.Data.Enums.LessonType lessonType) [0x00040] in D:\AlbidersSoftware\CSharp\Albiders Content MS\Albiders\WebClient\Services\LectureVideoService.cs:21 
  at WebClient.Pages.MathAccList.OnInitializedAsync () [0x00026] in D:\AlbidersSoftware\CSharp\Albiders Content MS\Albiders\WebClient\Pages\MathAccList.razor:18 
  at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2bed718 + 0x0013a> in <filename unknown>:0 
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2e3a0b0 + 0x000b6> in <filename unknown>:0 

Unhandled exception rendering component: TypeError: Failed to fetch

WebAssembly.JSException: TypeError: Failed to fetch

我做了一个测试,从我的 Blazor WebAssembly 应用向带有测试数据的操作方法发出请求,这对我来说效果很好。

[Route("[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
    [HttpGet]
    [Route("GetAllCustomers")]
    public async Task<IEnumerable<Customer>> GetAllCustomersAsync()
    {
        //for testing purpose

        return new List<Customer> { new Customer { Id = 1, Name = "Test1" }, new Customer { Id = 2, Name = "Test2" } };

        //return await _service.GetAllCustomersAsync();
    }
}

GetAllCustomers.razor

@page "/getallcustomers"
@using BlazorWasmApp1.Shared
@inject HttpClient _httpClient

<h3>Customer List</h3>

@if (customers == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var customer in customers)
            {
                <tr>
                    <td>@customer.Id</td>
                    <td>@customer.Name</td>
                </tr>
            }
        </tbody>
    </table>
}


@code {
    private Customer[] customers;

    protected override async Task OnInitializedAsync()
    {
        //call external API
        //_httpClient.BaseAddress = new Uri("https://localhost:44312/");


        //your API action would return a collection of Customer
        //you can try to call .GetFromJsonAsync<Customer[]>() to get the expected data
        //rather than get stream
        customers = await _httpClient.GetFromJsonAsync<Customer[]>($"Customer/GetAllCustomers");
    }
}

测试结果

要解决问题,请尝试:

  1. 在浏览器开发者工具网络选项卡中检查您请求的 URL,并确保您正在请求正确的端点

  2. 如果您的 ASP.NET Core Web API 项目托管在单独的站点上,请确保您配置并启用了 CORS 以允许来自 Blazor WebAssembly 应用程序的请求,并确保 API 是 运行

还要检查您的 api 是否从 HTTP 请求,将其更改为 https:它会起作用