IIS with my Blazor Webassembly ASP hosted (api calls) application throws Json Reader Exception trying to retrieve data from SQL Server

173 views Asked by At

My Blazor Webassembly ASP.NET Core 6.0 hosted app is published to IIS 10.0 (Windows 10). It has api calls to SQL Server. I can't get my collection (List<string>) populated from SQL server and Web Browser shows error:

fail: MyBlazorWebbAssemblyApp.Client.Pages.RedirectedAppeal.MyClientPage[0]
ExpectedJsonTokens Path: $ | LineNumber: 0 | BytePositionInLine: 0. :StackTrace:    at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& , JsonReaderException )
         at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
         at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonConverter , Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
         at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonReaderState& , Boolean , ReadOnlySpan`1 , JsonSerializerOptions , ReadStack& , JsonConverter )
         at System.Text.Json.JsonSerializer.ContinueDeserialize[List`1](ReadBufferState& , JsonReaderState& , ReadStack& , JsonConverter , JsonSerializerOptions )
         at System.Text.Json.JsonSerializer.<ReadAllAsync>d__65`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
         at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__4`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
         at WorkGroupProsecutor.Client.Pages.RedirectedAppeal.RedirectedPage.OnInitializedAsync() :#: System.Text.Json.JsonReaderException: ExpectedJsonTokens LineNumber: 0 | BytePositionInLine: 0.
         at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& , ExceptionResource , Byte , ReadOnlySpan`1 )
         at System.Text.Json.Utf8JsonReader.Read()
         at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )

I don't get this error when it runs in visual studio ! Or even if I run my published app on kestrel like so: dotnet myapp.dll Unfortunatelly i have to publish it to IIS.

The call chain:

Clients Page:

@inject HttpClient httpClient
@inject ILogger<MyClientPage> logger

@foreach (var period in periodsList) @*Some UI element where my List is shown:*@
{
   ...             
}

@code{
private List<string> periodsList = new();
protected override async Task OnInitializedAsync() //Where i get my error:
{
try
{
   periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");
}
catch(Exception ex)
{ logger.LogError($"{ex.Message} :StackTrace: {ex.StackTrace}" }
}

I also tryied rephrase the List population like this:

protected override async Task OnInitializedAsync() //Where i get my error:
{
   var periods = await httpClient.GetAsync($"api/RedirectedAppeal/{"Az"}/{2022}");
   periodsList = await periods.Content.ReadFromJsonAsync<List<string>>();
}

but got the same error :(

and like this:

periodsList = await JsonSerializer.DeserializeAsync<List<string>>(await httpClient.GetStreamAsync($"api/RedirectedAppeal/{"Az"}/{2022}"));

got me this error:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: net_http_message_not_success_statuscode, 500, Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500, Internal Server Error
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at BzrIIStest.Client.Pages.CatNamesPage.OnInitializedAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task , ComponentState )

Controller (RedirectedAppealController.cs):

[HttpGet("{district}/{year}")]
public async Task<IEnumerable<string>> Get(string district, int year)
{
   return await _appealRepository.GetRedirectedAppealPeriods(district, year);
}

Repository (AppealRepository.cs):

public async Task<IEnumerable<string>> GetRedirectedAppealPeriods(string district, int year)
{
    return await _dbContext.RedirectedAppeal
        .Where(a => a.District == district)
        .Where(a => a.YearInfo == year).Select(p => p.PeriodInfo).Distinct().ToListAsync(); 
}

Calls made in Swagger also return 500 Error: Internal Server Error

Response headers
 date: Tue,13 Dec 2022 10:02:00 GMT 
 server: Microsoft-IIS/10.0 
 transfer-encoding: chunked 
 x-powered-by: ASP.NET 

I tried:

I tried to use windows authentication and adding login and user to SQL Server (accordingly using connection string with Integrated Security=True and with User id and password)

I tried to twiggle IIS (.Net CLR Version - No Managed Code) by giving access in my SQL Server to it's App Pool

I have no firewall or port access issues.

Tried using GetFromJsonAsync and ReadFromJsonAsync as i mentioned above

periodsList = await httpClient.GetFromJsonAsync<List<string>>($"api/RedirectedAppeal/{"Az"}/{2022}");

vs

var periods = await httpClient.GetAsync($"api/RedirectedAppeal/{"Az"}/{2022}");
periodsList = await periods.Content.ReadFromJsonAsync<List<string>>();

vs

periodsList = await JsonSerializer.DeserializeAsync<List<string>>(await httpClient.GetStreamAsync($"api/RedirectedAppeal/{"Az"}/{2022}"));

In the controller i tried to wrap calls in IActionResult with Ok like so:

[HttpGet("{district}/{year}")]
public async Task<IActionResult> Get(string district, int year)
{
    return Ok(await _appealRepository.GetRedirectedAppealPeriods(district, year));
}

I also tryed to do it synchronously (even though HttpClient not a big fan of it >.<)

And i tried to use different browsers of course! No success :(

To reproduce the problem

I created simplified and cute :3 project to anyone who's willing to try it out - 1 table with 1 string field. Works perfectly on kestrel and wile running on express version vie Visual studio. All i'm trying to do is to make it work in a published IIS project. Migrations to generate DB via EF are included: Sample Project to recreate error

I have added Failed Request Tracing Rules, it doesn't show much unfortunatelly:

ModuleName="AspNetCoreModuleV2", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="The operation completed successfully.
 (0x0)", ConfigExceptionInfo=""

Any ideas? Thank you all in advance!

0

There are 0 answers