25

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

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Broad3857
  • 363
  • 1
  • 4
  • 10
  • 3
    Post the MyObject initialization code and type. You should not have to use ``, It should work with : `_http.PostJsonAsync("api/myRoute", myObject);` – agua from mars Mar 10 '20 at 20:30
  • 1
    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 guess – Broad3857 Mar 11 '20 at 10:31
  • 1
    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 console – Broad3857 Mar 11 '20 at 10:33
  • 1
    Is your service return a Json object ? The issue could be on the response – agua from mars Mar 11 '20 at 10:41

14 Answers14

17

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.

Lukas
  • 1,699
  • 1
  • 16
  • 49
8

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

Ogglas
  • 62,132
  • 37
  • 328
  • 418
5

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);
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
2

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

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

Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29
2

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.

Jabez
  • 795
  • 9
  • 18
2

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.

LW001
  • 2,452
  • 6
  • 27
  • 36
1

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);
Ogglas
  • 62,132
  • 37
  • 328
  • 418
1

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.

Zach J.
  • 204
  • 2
  • 7
1

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.

1

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

Usama Aziz
  • 169
  • 1
  • 10
1

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

Muhammad Saad
  • 186
  • 1
  • 13
1

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

Adnan
  • 906
  • 13
  • 30
1

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

Branden Barber
  • 1,717
  • 1
  • 17
  • 15
0

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

Christian Rios
  • 417
  • 5
  • 15