未经处理的异常渲染组件:'<'是价值的无效开始

发布于 2025-01-29 15:11:51 字数 12732 浏览 4 评论 0原文

刚从Blazor开始创建我的第一个应用程序,它是一个带有API的CRUD应用程序。但是我遇到了一个巨大的错误,我无法弄清楚什么是错误的,实际上是什么意思?考虑一下API链接吗?我已经尝试过组件:'<'对于Blazor Wasm的价值是无效的开端解决方案,但这些似乎对我来说都不适用。我正在使用EntityFramework中的VisualStudio 17.2.0中使用大型WebAssembly。

当我启动项目时,我会在页面底部收到此消息:

发生了一个未指导的错误。重新加载

blazor.webassembly.js:1 Crit: microsoft.aspnetcore.components.webassembly.rendering.webassemblyrenderer [100] 未经处理的异常渲染组件:'&lt;'是值的无效开始。路径:$ |亚麻布:0 | Bytepositioninline:0。 system.text.json.jsonexception:'&lt;'是值的无效开始。 路径:$ |亚麻布:0 | Bytepositioninline:0。---&GT; system.text.json.jsonreaderexception:'&lt;'是一个无效的开始 价值。亚麻布:0 | bytepositioninline:0。at system.text.json.throwhelper.throwjsonreaderexception(utf8jsonreader&amp; JSON,system.text.json.json.utf8jsonreader.consumevalue(byte marker)at System.text.json.json.json.utf8jsonreader.readfirsttoke(byte First)在System.text.json.text.json.json.json.json.json.json at System.text.json.text.json.text.json。 utf8jsonreader.readsinglesegresgresgement()at System.text.json.utf8jsonReader.Read()at System.text.json.serialization.jsonconverter 1 [[System.Collections.generic.generic.generic.generic.generic.generic.list.list 1 [trevidata.shared shared 。 ;读取器,jsonserialialoptions选项,readStack&amp; state) - 内部异常堆栈跟踪--- system.text.json.json.throwhelper.rethrowwithpath 1 [[System.Collections.generic.list 1 [[[trevidata.shared.models.ewons,trevidata.shared,version = 1.0.0.0,cultion = nubter = netial,publickeytoken = null]],系统。 private.corelib,版本= 6.0.0.0,文化=中性,publicKeyToken = 7cec85d7bea7798e]]。读者,jsonserialialoptions选项,ReadStack&amp; state)在system.text.json.jsonserializer.ReadCore [list 1](jsonConverter JSONCONVERTER,UTF8JSONREDER&amp;读者,jsonserialializoptions选项, ReadStack&amp;状态) system.text.json.jsonserializer.ReadCore [List 1](JSONREADERSTATE&amp; READERSTATE,Boolean IsfinalBlock,ReadonlySpan 1 Buffer, jsonserialializerOptions选项,ReadStack&amp;州,jsonconverter converterbase)at system.text.json.jsonserializer.continueDeserialize [list 1](deadBufferState&amp; bufferstate,jsonreaderstate&amp; jsonreaderstate,readStack&readstack&readstack,jsonconverter,jsonConverter,jsonserialialialialialialialialialialialialialialiageptions optys.st rystems.sonsclext.jsolial.teasy.jsallial.jesser.jesser.jesnizen; /code>> * [system.collections.generic.list< code> code> 1> [trevidata.shared.models.models.ewons,trevidata.shared,version = 1.0.0.0,culture =中性,publickeytoken = null] 。 .LIST 1 [[[trevidata.shared.models.models.ewons,trevidata.shared,版本= 1.0.0.0,culture =中性,public keytrekek = null]],system.private.corelib,版本= 6.0.0.0.0中性,publicKeyToken = 7cec85d7bea7798e]]。 .ewons, trevidata.shared,版本= 1.0.0.0,文化=中性, publicKeyToken = null]],system.private.corelib,版本= 6.0.0.0, 文化=中性,publicKeyToken = 7cec85d7bea7798e]]。movenext()at trevidata.client.pages.ewondetails.getuser()in C:\ Users \ Toonw \ source \ repos \ trevidata \ trevidata \ client \ pem \ pages \ ewondetails.razor:line 73在trevidata.client.pages.ewondetails.nitializedasync()中 C:\ Users \ Toonw \ source \ repos \ trevidata \ trevidata \ client \ pem \ pages \ ewondetails.razor:line 69 at microsoft.aspnetcore.components.componentbase.runinitandsetparametersasync() 在 microsoft.aspnetcore.components.rendertree.renderer.getErrorhandledTask(任务 taskohandle,componentState拥有componentState) 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.5.wc6fu8n2ms.js:1 $ func219 @ 00971E46:0x1a490 $ func167 $ func2812 @ 00971E46:0xABF01 $ func1616 @ 00971E46:0x6fcc2 $ func1620 @ 00971E46:0x7032f $ mono_wasm_invoke_method @ 00971E46:0x969d Module._Mono_wasm_invoke_method @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 MANSED_BINDINGS_SETTASKSOURCERESULT @ MANSED_BINDINGS_SETTASKSOURCERESULT:17(匿名) @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 promise.then(async) _wrap_js_thenable_as_task @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 _js_to_mono_obj @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 _mono_wasm_invoke_js_with_args @ dotnet.6.0.5.5.wc6fu8nn2ms.js:1 $ func219 @ 00971E46:0x1A4449 $ func167 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.5.wc6fu8nn2ms.js:1 manded_bindings_settasksourceresult @ MANSED_BINDINGS_SETTASKSOURCERESULT:17(匿名) @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 promise.then(async) _wrap_js_thenable_as_task @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 _js_to_mono_obj @ dotnet.6.0.5.5.wc6fu8n2ms.js:1 _mono_wasm_invoke_js_with_args @ dotnet.6.0.5.5.wc6fu8nn2ms.js:1 $ func219 @ 00971E46:0x1A4449 $ func167 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.5.wc6fu8n2ms.js:1 托管__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 (匿名) @ blazor.webassembly.js:1 ve @ blazor.webassembly.js:1我们 @ blazor.webassembly.js:1(匿名) @ blazor.webassembly.js:1 (匿名) @ 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();
        }
    }
}

just started with Blazor created my first app its a CRUD app with api. But i get this huge error and i can't figure out what is wrong and what it actual means? think something with the api links? I've tried the Unhandled exception rendering component: '<' is an invalid start of a value for Blazor WASM solutions but none of these seems to work for me. I'm using the blazor webassembly in visualstudio 17.2.0 with entityframework.

When i start my project i get this message at the bottom of my page :

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

Here is my code.

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();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

春花秋月 2025-02-05 15:11:51

我很确定该错误在getfromjsonasync呼叫什么都不返回 - 有很多代码值得通过!

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

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

url“ API/用户”。

因此,请整理您的控制器名称或电话。

您应该始终与Postman一起测试您的API!

I'm pretty sure the error is in the GetFromJsonAsync call returning nothing - there's a lot of code to plough through!

You are calling api/ewon/, but your controller is defined as:

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

which has the url "api/user".

So sort out your controller name or your calls.

You should always test your APIs with Postman!

神也荒唐 2025-02-05 15:11:51

我遇到了这个错误,但是我的控制器名称正确,并且在发现HTTPCLIENT的“ getFromjSonAsync”后,我将其修复了。

因此,如果您的控制器未明确路由,则可能需要使其与控制器名称完全一样,因此情况将与您作为字符串所传递的内容匹配。

所以这条线将是
ewonlist =等待http.getFromjSonAsync&lt; list&gt;(“ api/ewon”);

其他一些方法可能是配置JSON选项,因此序列化/进行验证可能是不敏感的。

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = true;
});

I got this error but mine I had my controller name correct and I fixed it after I found out that "GetFromJsonAsync" of the HttpClient is case sensitive.

So if your controller is not routed explicitly, you might want to make it be exactly like the Controller name so the case will match what you pass as a string.

So this line will be
ewonList = await Http.GetFromJsonAsync<List>("api/Ewon");

Some other way might be configuring the Json options so serialization/Deserialization can be case insensitive.

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.PropertyNameCaseInsensitive = true;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文