asp.net-core - 如何解决 Blazor 上的 "TypeError: Failed to fetch"错误?

标签 asp.net-core asp.net-web-api blazor blazor-client-side

我正在尝试从我的 Blazor 应用程序向我的 ASP.NET Core API 发送 HTTP 请求。我到处都有断点。应用程序在 API Controller 上的操作方法返回后立即给出异常。我对 .NET 总体上很熟悉,但是,我无法破译错误消息。
Blazor http 调用:

var response = await _httpClient.GetStreamAsync($"Customer/GetAllCustomers");
ASP.NET Core API Controller 操作:
[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");
    }
}
测试结果
enter image description here
要解决此问题,请尝试:
  • 在浏览器开发人员工具网络选项卡中检查您的请求的 URL,并确保您正在向正确的端点发出请求
  • 如果您的 ASP.NET Core Web API 项目托管在单独的站点上,请确保配置并启用 CORS 以允许来自 Blazor WebAssembly 应用程序的请求,并确保 API 正在运行
  • 关于asp.net-core - 如何解决 Blazor 上的 "TypeError: Failed to fetch"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65084846/

    相关文章:

    asp.net-core - Blazor 在上一个操作完成之前在此上下文中启动了第二个操作

    Blazor WASM 没有达到断点

    asp.net-core - 如何重新运行 dnx . kestrel 命令对任何文件进行更改?

    .net - .NET Core 3.x 中的多个运行状况检查端点

    jquery - getJSON Web API 可在开发服务器上运行,但 IIS Express 7.5 抛出 404 未找到

    c# - 传入字典的模型项的类型为 'System.Net.Http.HttpResponseMessage' ,

    c# - 如何将多个参数传递/接收到 RESTful Web API GET 方法?

    c# - 从 ASP.NET Core api 从 Blazor 客户端应用程序下载文件

    c# - 上传到天蓝色存储返回空文件

    c# - 使用 open id connect server 在 asp.net core 中检索声明