未处理的异常呈现组件:“<”是值的无效开头

Unhandled exception rendering component: '<' is an invalid start of a value

刚开始使用 Blazor 创建了我的第一个应用程序,它是一个带有 api 的 CRUD 应用程序。但是我得到了这个巨大的错误,我无法弄清楚哪里出了问题以及它的实际含义是什么?想想 api 链接?我已经尝试了 Unhandled exception rendering component: '<' is an invalid start of a value for Blazor WASM 解决方案,但其中 none 似乎对我有用。我在 visualstudio 17.2.0 中使用 blazor webassembly entityframework.

当我开始我的项目时,我在页面底部收到这条消息:

An unhandled error has occurred. Reload

blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0. System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0. ---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0. at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan1 bytes) at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker) at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first) at System.Text.Json.Utf8JsonReader.ReadSingleSegment() at System.Text.Json.Utf8JsonReader.Read() at System.Text.Json.Serialization.JsonConverter1[[System.Collections.Generic.List1[[TreviData.Shared.Models.Ewons, TreviData.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) --- End of inner exception stack trace --- at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex) at System.Text.Json.Serialization.JsonConverter1[[System.Collections.Generic.List1[[TreviData.Shared.Models.Ewons, TreviData.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[List1](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[List1](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase) at System.Text.Json.JsonSerializer.ContinueDeserialize[List1](ReadBufferState& bufferState, JsonReaderState& jsonReaderState, ReadStack& readStack, JsonConverter converter, JsonSerializerOptions options) at System.Text.Json.JsonSerializer.<ReadAllAsync>d__651[[System.Collections.Generic.List1[[TreviData.Shared.Models.Ewons, TreviData.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__41[[System.Collections.Generic.List1[[TreviData.Shared.Models.Ewons, TreviData.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__131[[System.Collections.Generic.List`1[[TreviData.Shared.Models.Ewons, TreviData.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() at TreviData.Client.Pages.EwonDetails.GetUser() in C:\Users\toonw\source\repos\TreviData\TreviData\Client\Pages\EwonDetails.razor:line 73 at TreviData.Client.Pages.EwonDetails.OnInitializedAsync() in C:\Users\toonw\source\repos\TreviData\TreviData\Client\Pages\EwonDetails.razor:line 69 at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync() at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState) window.Module.s.printErr @ blazor.webassembly.js:1 Fe._internal.dotNetCriticalError @ blazor.webassembly.js:1 St @ blazor.webassembly.js:1 _mono_wasm_invoke_js_blazor @ dotnet.6.0.5.wc6fu8n2ms.js:1 $func219 @ 00971e46:0x1a490 $func167 @ 00971e46:0xce5e $func166 @ 00971e46:0xbd71 $func2812 @ 00971e46:0xabf01 $func1616 @ 00971e46:0x6fcc2 $func1620 @ 00971e46:0x7032f $mono_wasm_invoke_method @ 00971e46:0x969d Module._mono_wasm_invoke_method @ dotnet.6.0.5.wc6fu8n2ms.js:1 managed_BINDINGS_SetTaskSourceResult @ managed_BINDINGS_SetTaskSourceResult:17 (anonymous) @ dotnet.6.0.5.wc6fu8n2ms.js:1 Promise.then (async) _wrap_js_thenable_as_task @ dotnet.6.0.5.wc6fu8n2ms.js:1 _js_to_mono_obj @ dotnet.6.0.5.wc6fu8n2ms.js:1 _mono_wasm_invoke_js_with_args @ dotnet.6.0.5.wc6fu8n2ms.js:1 $func219 @ 00971e46:0x1a449 $func167 @ 00971e46:0xce5e $func166 @ 00971e46:0xbd71 $func2812 @ 00971e46:0xabf01 $func1616 @ 00971e46:0x6fcc2 $func1620 @ 00971e46:0x7032f $mono_wasm_invoke_method @ 00971e46:0x969d Module._mono_wasm_invoke_method @ dotnet.6.0.5.wc6fu8n2ms.js:1 managed_BINDINGS_SetTaskSourceResult @ managed_BINDINGS_SetTaskSourceResult:17 (anonymous) @ dotnet.6.0.5.wc6fu8n2ms.js:1 Promise.then (async) _wrap_js_thenable_as_task @ dotnet.6.0.5.wc6fu8n2ms.js:1 _js_to_mono_obj @ dotnet.6.0.5.wc6fu8n2ms.js:1 _mono_wasm_invoke_js_with_args @ dotnet.6.0.5.wc6fu8n2ms.js:1 $func219 @ 00971e46:0x1a449 $func167 @ 00971e46:0xce5e $func166 @ 00971e46:0xbd71 $func2812 @ 00971e46:0xabf01 $func1616 @ 00971e46:0x6fcc2 $func1614 @ 00971e46:0x6fc34 $func967 @ 00971e46:0x50685 $func219 @ 00971e46:0x1a449 $func167 @ 00971e46:0xce5e $func166 @ 00971e46:0xbd71 $func2812 @ 00971e46:0xabf01 $func1616 @ 00971e46:0x6fcc2 $func1620 @ 00971e46:0x7032f $mono_wasm_invoke_method @ 00971e46:0x969d Module._mono_wasm_invoke_method @ dotnet.6.0.5.wc6fu8n2ms.js:1 managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_BeginInvokeDotNet @ managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_BeginInvokeDotNet:19 beginInvokeDotNetFromJS @ blazor.webassembly.js:1 b @ blazor.webassembly.js:1 e.invokeMethodAsync @ blazor.webassembly.js:1 (anonymous) @ blazor.webassembly.js:1 ve @ blazor.webassembly.js:1 we @ blazor.webassembly.js:1 (anonymous) @ blazor.webassembly.js:1 (anonymous) @ blazor.webassembly.js:1 onGlobalEvent @ blazor.webassembly.js:1

这是我的代码。

AddEwon.Razor

    @page "/ewon/add/"
    @page "/ewon/edit/{Id:int}"
    @using TreviData.Shared.Models
    @inject HttpClient Http
    @inject NavigationManager NavigationManager
    <h1>@Title Ewon</h1>
    <hr />
    <EditForm Model="@ewon" OnValidSubmit="SaveEwon">
        <DataAnnotationsValidator />
        <div class="mb-3">
            <label for="Name" class="form-label">EwonName</label>
            <div class="col-md-4">
                <InputText class="form-control" @bind-Value="ewon.EwonName" />
            </div>
            <ValidationMessage For="@(() => ewon.EwonName)" />
        </div>
        <div class="mb-3">
            <label for="Address" class="form-label">ApiKey</label>
            <div class="col-md-4">
                <InputText class="form-control" @bind-Value="ewon.ApiKey" />
            </div>
            <ValidationMessage For="@(() => ewon.ApiKey)" />
        </div>
    
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Save</button>
            <button class="btn btn-light" @onclick="Cancel">Cancel</button>
        </div>
    </EditForm>
    @code {
        [Parameter]
        public int Id { get; set; }
        protected string Title = "Add";
        protected Ewons ewon = new();
        protected override async Task OnParametersSetAsync()
        {
            if (Id != 0)
            {
                Title = "Edit";
                ewon = await Http.GetFromJsonAsync<Ewons>("api/ewon/" + Id);
            }
        }
        protected async Task SaveEwon()
        {
            if (ewon.Id != 0)
            {
                await Http.PutAsJsonAsync("api/ewon", ewon);
            }
            else
            {
                await Http.PostAsJsonAsync("api/ewon", ewon);
            }
            Cancel();
        }
        public void Cancel()
        {
            NavigationManager.NavigateTo("/fetchewondetails");
        }
    }

FetchData.Razor

  @page "/ewondetails"
@using TreviData.Shared.Models
@inject HttpClient Http
<h1>Ewon Data</h1>
<p>Ewons api-keys.</p>
<div class="row">
    <div class="col-md-6">
        <a href='/ewon/add' class="btn btn-primary" role="button">
            <i class="fas fa-ewon-plus"></i>
            Add Ewon
        </a>
    </div>
    <div class="input-group col">
        <input type="text" class="form-control" placeholder="Search Ewon by name"
               @bind="SearchString" @bind:event="oninput" @onkeyup="FilterUser" />
        @if (SearchString.Length > 0)
        {
            <div class="input-group-append">
                <button class="btn btn-danger" @onclick="ResetSearch">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        }
    </div>
</div>
<br />
@if (ewonList == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table table-striped align-middle table-bordered">
        <thead class="table-success">
            <tr>
                <th>Id</th>
                <th>Ewon Name</th>
                <th>Api key</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var e in ewonList)
            {
                <tr>
                    <td>@e.Id</td>
                    <td>@e.EwonName</td>
                    <td>@e.ApiKey</td>
                    <td>
                        <a href='/ewon/edit/@e.Id' class="btn btn-outline-dark" role="button">
                            Edit
                        </a>
                        <a href='/ewon/delete/@e.Id' class="btn btn-outline-danger" role="button">
                            Delete
                        </a>
                    </td>
                </tr>
            }
        </tbody>

    </table>
}
@code {
    protected List<Ewons> ewonList = new();
    protected List<Ewons> searchEwonData = new();
    protected Ewons ewon = new();
    protected string SearchString { get; set; } = string.Empty;
    protected override async Task OnInitializedAsync()
    {
        await GetUser();
    }
    protected async Task GetUser()
    {
        ewonList = await Http.GetFromJsonAsync<List<Ewons>>("api/ewon");
        searchEwonData = ewonList;
    }
    protected void FilterUser()
    {
        if (!string.IsNullOrEmpty(SearchString))
        {
            ewonList = searchEwonData
                .Where(x => x.EwonName.IndexOf(SearchString, StringComparison.OrdinalIgnoreCase) != -1)
                .ToList();
        }
        else
        {
            ewonList = searchEwonData;
        }
    }
    protected void DeleteConfirm(int Id)
    {
        ewon = ewonList.FirstOrDefault(x => x.Id == Id);
    }
    public void ResetSearch()
    {
        SearchString = string.Empty;
        ewonList = searchEwonData;
    }

}

EwonController

using TreviData.Server.InterFaces;
using TreviData.Shared.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace TreviData.Server.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IEwons _IEwons;
        public UserController(IEwons iEwons)
        {
            _IEwons = iEwons;
        }
        [HttpGet]
        public async Task<List<Ewons>> Get()
        {
            return await Task.FromResult(_IEwons.GetEwonDetails());
        }
        [HttpGet("{Id}")]
        public IActionResult Get(int id)
        {
            Ewons ewon = _IEwons.GetEwonData(id);
            if (ewon != null)
            {
                return Ok(ewon);
            }
            return NotFound();
        }
        [HttpPost]
        public void Post(Ewons ewon)
        {
            _IEwons.AddEwon(ewon);
        }
        [HttpPut]
        public void Put(Ewons ewons)
        {
            _IEwons.UpdateEwonDetails(ewons);
        }
        [HttpDelete("{Id}")]
        public IActionResult Delete(int id)
        {
            _IEwons.DeleteEwon(id);
            return Ok();
        }
    }
}

我很确定错误出在 GetFromJsonAsync 没有返回任何内容的调用中 - 有很多代码需要仔细研究!

您正在调用 api/ewon/,但您的控制器定义为:

    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
/....

其中有 url“api/user”。

所以整理一下您的控制器名称或电话。

您应该始终使用 Postman 测试您的 API!