System.Text.Json.JsonException: The input does not contain any JSON tokens
Asked Answered
S

16

32

I'm just trying to use a Http POST method in a Blazor app through

public async Task CreateUnit(UnitEntity unit)
{
    await _http.PostJsonAsync<UnitEntity>("api/units", unit);
}

_http and myObject have been defined elsewhere, but I'm getting this weird error. Can anyone help? This is the closest thing I could find elsewhere: https://github.com/dotnet/runtime/issues/30945.

The full error message is

System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

And it here's the stack

enter image description here

Sanies answered 10/3, 2020 at 17:32 Comment(6)
Post the MyObject initialization code and type. You should not have to use <MyType>, It should work with : _http.PostJsonAsync("api/myRoute", myObject);Sandra
I've edited the whole method in at the top code block here. I know that the UnitEntity I use is valid because it's the same one I use for tests in the DAL without going through the service. I'm thinking it could be something to do with async or serialization, but that's just a guessSanies
The weird thing is that debugging both the UI and the service doesn't pick up the exception at all. It only shows in the browser consoleSanies
Is your service return a Json object ? The issue could be on the responseSandra
In my case I tried to read Request.Body two times. Solution: #54443053Coypu
@Coypu bless you, maybe that needs to be an answer for visibilityMidwinter
E
21

Another reason this error could pop up, as it did for me, is simply because the API endpoint doesn't exist because it was misspelled.

Elliot answered 21/12, 2020 at 17:7 Comment(0)
M
12

In my case the code was doing this:

var json = await response.Content.ReadAsStringAsync();
var result = JsonObject.Parse(json); // threw the exception mentioned in the question

Why did that happen? That's because json value was an empty string "". Parse fails with an empty string.

Fixed it doing this simple change:

var json = await response.Content.ReadAsStringAsync();
var result = string.IsNullOrEmpty(json) ? null : JsonObject.Parse(json);
Microminiaturization answered 23/6, 2022 at 15:9 Comment(0)
T
10

I got a similar error in Program.cs Main method CreateHostBuilder(args).Build();:

System.FormatException: 'Could not parse the JSON file.'

JsonReaderException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0.

For me it turned out to be the local secrets.json file that not contained a valid json object.

https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#secret-manager

Because of this I could not see any errors in Git or rollback to a working commit since the file is not checked in.

Solved by adding an empty object to the file via Visual Studio - right click the project in solution explorer and select Manage User Secrets:

{

}

https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#manage-user-secrets-with-visual-studio

Thunderpeal answered 27/9, 2021 at 20:59 Comment(0)
D
4

i had similar issue and the problem to check if the json string you are readying is empty, null, or bad formatted. debug to the code line where you are reading data into string before deserialize or serialize call.

Desmund answered 10/2, 2022 at 8:27 Comment(0)
D
4

I was also having the same error in this line: CreateWebHostBuilder(args).Build().Run();.

The solution is to right click on your project file in Visual Studio, select the option manage secret file and if that file (secret.json) is empty then put {} into that file.

Dodecanese answered 31/7, 2023 at 4:3 Comment(0)
P
3

For me, this error occurred when calling FindByNameAsync of UserManager.

Sounds silly, but the database connection string in the appsettings was wrong!

Patriotism answered 20/8, 2021 at 13:27 Comment(0)
T
2

I got this error when communicating between two APIs.

request = await req.DeserializeRequestBodyAsync<MyDto>(jsonSerializerOptions);

Turned out the code below did not actually send any values:

httpRequestMessage.Content = JsonContent.Create(myDto);
var httpClient = _clientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);

I had to manually specify:

await httpRequestMessage.Content.LoadIntoBufferAsync();

Like this:

httpRequestMessage.Content = JsonContent.Create(myDto);
await httpRequestMessage.Content.LoadIntoBufferAsync();
var httpClient = _clientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
Thunderpeal answered 22/6, 2021 at 17:47 Comment(0)
I
2

Late answer - but I ran into this using Blazor WebAssembly with Browser Link (trying to get Hot Reload to work). Turns out it's an issue loading the appsettings and Browser Link was expecting the secrets file. I fixed by right clicking the Server project and copy/pasting my appsettings values into the secrets file.

Insane answered 11/11, 2021 at 15:4 Comment(0)
N
2

In my case, I was passing the id of my object along with the object itself in the url of the put request to an API and faced the same exception. It turned out that it was not necessary to pass the id (as it was retrieved from the object itself, in fact it was not present in the method signature). Removing the id solved the problem.

Nairn answered 29/12, 2021 at 10:24 Comment(0)
F
2

This error occurred when communicating between client and web API.

API code:

public async Task<IActionResult> PostAsync(object review)
{
    return Ok();
}

Client code:

var res = await _client.PostAsJsonAsync("api/reviews", review);
if (res.IsSuccessStatusCode)
{
    var myObject = await res.Content.ReadFromJsonAsync<MyObject>(); //this line threw mentioned error
}

Turned out that the API endpoint was returning something different compared to what I was trying to read from JSON i.e. I was trying to read MyObject but API was returning ActionResult

Fighter answered 22/7, 2022 at 16:26 Comment(0)
P
2

In my case database column was marked not null and I was passing null in API.

Paleobiology answered 31/1, 2023 at 3:59 Comment(0)
H
2

I was missing a comma (,) at the end of a line in appsettings.json

Hirz answered 12/3, 2023 at 13:36 Comment(0)
L
2

In my case we were missing Content-Length header our request, which should be the length of your json input

Labbe answered 11/4, 2023 at 18:12 Comment(0)
Q
1

Got this error because I did not have access to the endpoint.

Quetzalcoatl answered 17/8, 2023 at 3:21 Comment(0)
C
1

And I got it because the endpoint expected a parameter, but I was not passing any.

Copulative answered 4/4, 2024 at 5:10 Comment(0)
U
0

I got this error because the fetch on the front end was specifying Content-Type: application/json for a GET (no body)

Ul answered 23/7, 2024 at 16:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.