0

I am using Microsoft.AspNetCore.Blazor.HttpClient to perform requests on my API endpoints.

If the below call finds nothing it raises an exception.

using var client = auth.GetMyToken();
return await Task.Run(async () => await client.GetJsonAsync<MyModel>($"getsomething/{id}"));

The error says:

{"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."}

I am guessing it does this because the return is not JSON (it's nothing)

I'd rather not wrap a Try{} block around it to deal with no records found.

How can I amend this to return null (or an empty model) if no record is found?

15
  • 1
    Are you using the latest version of Blazor? It has switched to GetFromJsonAsync Commented Sep 21, 2020 at 13:50
  • This a pre-release library so different to the one your are referring to I think: nuget.org/packages/Microsoft.AspNetCore.Blazor.HttpClient Commented Sep 21, 2020 at 13:57
  • Define "finds nothing" please. Commented Sep 21, 2020 at 14:11
  • So, if you make a GetById endpoint and you send in an id that does not exist. Commented Sep 21, 2020 at 14:16
  • 2
    3.2 was released so you should not need (and should not use) that package anymore. Update and see if this still is a question. Commented Sep 21, 2020 at 14:44

2 Answers 2

3

An empty result should not give an error.

The old Json API reports

The input does not contain any JSON tokens.

and the new one

The provided ContentType is not supported;

They are both caused by trying to parse HTML as Json. This is 'normal' (not good) for Blazor WebAssembly when the API is on the same host (as in the Hosted template).

Any error in the url for your API results in rendering the MainLayout with "sorry, nothing here" as the body. You will not get a 404.

So, debug your routing.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes that is correct. Blazor GetFromJsonAsync will not handle empty Json result. Instead, you should do this when returning result in your web api controller:

public async Task<IActionResult> GetQuote(string quoteid)
    {
        int QuoteID = int.Parse(quoteid);
        var quote = await _dataContext.tblQuotes 
                            .Where(x => x.ID == QuoteID)
                            .SingleOrDefaultAsync();
                           
        if (quote == null) //DO NOT RETURN NULL
            quote = new Quote();
        return Ok(quote);

Notice here that if quote is null, I return a new Quote(), so the quote object is not null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.