EN VI

C# - Blazor - Fetching from Db Internal Server Error?

2024-03-14 01:00:04
How to C# - Blazor - Fetching from Db Internal Server Error

I have a blazor web app (Auto) that fetches items from the db on the client side. I have already created Services and controllers to fetch all items which works but when i try and search for specific items it breaks and i get this error:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Response status code does not indicate success: 500 (Internal Server Error).
System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<<FromJsonAsyncCore>g__Core|12_0>d`2[[System.Collections.Generic.List`1[[Design_A_Bear.Models.Item, Design_A_Bear.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Text.Json.JsonSerializerOptions, System.Text.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]].MoveNext()
   at Design_A_Bear.Services.ClientItemService.GetItemsByCategory(String category) in C:\Users\User\source\repos\Design_A_Bear_2.0\Design_A_Bear.Services\ClientItemService.cs:line 56
   at Design_A_Bear.Client.Pages.Items.Browse.OnInitializedAsync() in C:\Users\User\source\repos\Design_A_Bear_2.0\Design_A_Bear\Design_A_Bear.Client\Pages\Items\Browse.razor:line 49
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

Here is the relevant code:

IItemService.CS:

Task<List<Item>> GetItemsByCategory(string category);

ItemService.CS:

public async Task<List<Item>> GetItemsByCategory(string category)
{
    List<Item>items = await _db.Items.Where(item => item.Category == category).ToListAsync();
    return items;
}

ClientItemService.cs

public async Task<List<Item>> GetItemsByCategory(string category)
{
    var result = await  _httpClient.GetFromJsonAsync<List<Item>>($"/api/Item/{category}");
    return result;
}

ItemController.cs

[HttpGet("{category}")]
public async Task<ActionResult> GetItemsByCategory(string category)
{
    var items = await _itemServices.GetItemsByCategory(category);
    return Ok(items);
}

Update: this is the error i am getting:

An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints. Matches:

Design_A_Bear.Controllers.ItemController.GetItemsByCategory (Design_A_Bear)
Design_A_Bear.Controllers.ItemController.GetItemById (Design_A_Bear)

This is becuase i have two get functions which takes in a parameter. How can i select which one i want?


        public async Task<List<Item>> GetItemsByCategory(string category)
        {
            var result = await  _httpClient.GetFromJsonAsync<List<Item>>($"/api/Item/{category}");
            return result;
        }

        public async Task<Item> GetItemById(int id)
        {
            var result = await _httpClient.GetFromJsonAsync<Item>($"/api/Item/{id}");
            return result;
        }

Solution:

To differentiate between the two GET endpoints on the same controller, you need to add routing to each endpoint.

For the first endpoint

[Route("category/{category}")]

and for the second endpoint

[Route("items/{id}")]

something along these lines above the controller methods should solve the issue of having two GET endpoints.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login