Cannot reach controller from razor page

Not sure I picked the correct category, but my error suggest that it is web assembly.

I have a working api, tested with swagger. When I try to add the razor page, it seems to not to be able to access the controller to fetch the data.

Trying to see why I am getting errors pulling back data to my razor page.
I created a simple swagger to pull back /api/Dates. Works as expected.

This error is hard to see where it is coming from. I can see that it doesn’t even reach the controller.

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[[CaisClientServerApp.Shared.Dates[], CaisClientServerApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].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[[CaisClientServerApp.Shared.Dates[], CaisClientServerApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[Dates[]](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[Dates[]](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase)
at System.Text.Json.JsonSerializer.d__201[[CaisClientServerApp.Shared.Dates[], CaisClientServerApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__31[[CaisClientServerApp.Shared.Dates[], CaisClientServerApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at System.Net.Http.Json.HttpClientJsonExtensions.d__9`1[[CaisClientServerApp.Shared.Dates[], CaisClientServerApp.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at CaisClientServerApp.Client.Pages.FetchDates.OnInitializedAsync() in C:\codebase\CaisClientServerApp\Client\Pages\FetchDates.razor:line 42
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

Controller:
using CaisClientServerApp.Server.Services.App;
using CaisClientServerApp.Server.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using CaisClientServerApp.Server.Controllers;

namespace cat_cais_web_api.Server.Controllers
{

[Route("api/[controller]")]
[ApiController]
public class DatesController : Controller
{
    private IMemoryCache _cache;
    private readonly ILogger<DatesController> _logger;
    private readonly IDateService _datesService;

    public DatesController(IDateService datesService, IMemoryCache cache, ILogger<DatesController> logger)
    {
        _cache = cache;
        _logger = logger;
        _datesService = datesService;
    }

    // GET: api/dates
    [HttpGet]
    [Authorize]
    public IActionResult Get()
    {

        try
        {

            var result = _datesService.getDates();

            return Ok(JsonConvert.SerializeObject(result, Formatting.Indented));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error Getting Date");
            return BadRequest();
        }

    }
}

}

needed to remove @ to even post this

RAZOR page:

page "/fetchdates"
using CaisClientServerApp.Shared
inject HttpClient Http

Core Dates

This component demonstrates fetching dates from the server.

@if (dates == null)
{

Loading...


}
else
{

<table class="table">
    <thead>
        <tr>
            <th>psysdate</th>
            <th>sysdate</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var coredate in dates)
        {
        <tr>
            <td>@coredate.Psysdate.ToShortDateString()</td>
            <td>@coredate.Sysdate.ToShortDateString()</td>
        </tr>
        }
    </tbody>
</table>

}

@code {
private Dates[] dates;

protected override async Task OnInitializedAsync()
{
    dates = await Http.GetFromJsonAsync<Dates[]>("api/Dates");
}

}

Hey @Gary_Kagan,

This forum supports markdown, check the forum FAQ for reference.

thanks anyway, been trying to evaluate this product for some time with no good results.

The exception is raised most probably since your API call returns HTML and this cannot be parsed as JSON. You can use your browser tools network tab to inspect the requests.

ok, but my main issue is that while debugging starting from the razor page, the code NEVER steps into the controller in the first place.

I’ll repeat my suggestion again: use your browser tools network tab to inspect what exactly is requested.

also, it does return JSON

return Ok(JsonConvert.SerializeObject(result, Formatting.Indented));

Responses

Curl

curl -X 'GET' \
  'https://localhost:44398/api/Dates' \
  -H 'accept: */*'

Request URL

https://localhost:44398/api/Dates

Server response

Code Details
200 ##### Response body

Download

[
  {
    "psysdate": "2022-09-07T00:00:00",
    "sysdate": "2022-09-08T00:00:00"
  }
]
Response headers

content-encoding: gzip content-type: text/plain; charset=utf-8 date: Thu,08 Sep 2022 15:26:07 GMT persistent-auth: true server: Microsoft-IIS/10.0 transfer-encoding: chunked vary: Accept-Encoding x-powered-by: ASP.NET|

Responses

Code Description Links
200 Success

As far as I can see the user should be authorized to access the controller, if you attempt to call this with unauthorized user you will get 401 server error in HTML format and the client service will fail with JSON parse error.

ok, I'll remove all authorization and try again. The fact that I get a 200 success with results in swagger I thought that the issue would have nothing to do with Authorize.