22

I have a Blazor Webassembly project with a controller method as follows:

[HttpGet]
    public async Task<List<string>> GetStatesForProfile()
    {
        IConfigurationSection statesSection = configuration.GetSection("SiteSettings:States");
        var sections = statesSection.GetChildren();
        var states = statesSection.GetChildren().Select(s => s.Key).ToList<string>();
        return states;            
    }

The razor page calls this method:

private async Task<bool> GetStatesModel()
{
    try
    {
        States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");            
        ...
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex.Message}, Inner: {ex.InnerException.Message}");
    }

I get this Exception:

Exception: '<' is an invalid start of a value.

I read these values from appsettings.json file, And there is no '<' in values.

{      
  "SiteSettings": {    
    "States": {
      "New York": ["NYC"],
      "California": ["Los Angeles", "San Francisco"]
    }
 }

Also I put a breakpoint in the controller method and it doesn't hit. What is this error? Is it from parsing json? and how to resolve this?

H H
  • 263,252
  • 30
  • 330
  • 514
mz1378
  • 1,957
  • 4
  • 20
  • 40

18 Answers18

15

I had a very similar problem.

In the end it turned out that my browser had cached the HTML error page (I guess I had some problems with the code when I first tried it). And no matter how I tried fixing the code I still only got the error from cache. Clearing my cache also cleared the problem.

Lauri Peltonen
  • 1,432
  • 15
  • 29
  • 1
    I was messing with HTTP endpoints, then got a duplicate endpoint error due to my mistake. After this, I always got the same error like you did, even after reverting my code to an older working version. The only thing which fixed it was following your answer and clearing my browser cache. – drojf May 24 '21 at 04:32
  • 1
    Wow wow wow. I wasted at least an hour on this today. Ugh. Please fix this Blazor. – Grandizer Feb 18 '22 at 17:48
13

It happens when you're trying to access an API that doesn't exist. You have to check your API project connectionstring under AppSettings and make sure it's correct and running. If it's a Blazor project, you can set it as your default project, execute and see if you get a json response.

9

Most probably the response you are receiving is html instead of actual JSON format for the endpoint you are requesting. Please check that.

An as HTML usually starts with <html> tag, the JSON validator fails on the very first character.

You should also clear any cache, that might be interfering with the returned data. (this has helped people resolve this same issue)

Ron
  • 5,900
  • 2
  • 20
  • 30
  • How this is possible? The method returns a List and values as shown are not HTML? – mz1378 Apr 28 '20 at 19:09
  • 1
    Did you try to print `States` once you get the response, so you can confirm what actually it returns? – Ron Apr 28 '20 at 19:10
  • I the server I tried to put the codes in another action method that works, and there, values naturally show in the List states = ... But in the client I face an exception in the same line and can not print received data. – mz1378 Apr 28 '20 at 19:27
  • The problem is in the source line: http.GetJsonAsync>, GetJsonAsync expects a regular class as its type parameter not a generic class, So List is treated as a regular class not a generic class, Since .Net does not let the less than charachter contained in the class name this error is raised. – mz1378 Jun 09 '20 at 10:10
  • This [thread](https://stackoverflow.com/questions/63861247/blazors-webapi-returns-text-html-instead-of-application-json) helped me solve the problem – Cedervall Mar 08 '23 at 10:28
6

I know this is an old question, but it's one of the top results when Googling the error.

I've just spent more time than I care to admit to tracking down this error. I had a straightforward Blazor hosted app, basically unchanged from the template. It worked just fine when run locally, but when published to my web host API calls failed. I finally figured out that the problem was that I was running the publish from the Client project. When I changed to the Server project it worked properly.

Hopefully my long frustration and slight stupidity will save someone else making a similar mistake.

Slugsie
  • 851
  • 1
  • 7
  • 17
5

This error indicates a mismatch of the project targeting framework version and installed runtime on the machine. So make sure that the target framework for your project matches an installed runtime - this could be verified by multiple means; one of them is to check out the Individual Components tab of the Visual Studio Installer and lookup the target version.

E.g., there is the TargetFramework attribute in the proj file:

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

Then launch the Visual Studio Installer, click Modify, and visit the Individual Components tab:

Needed framework not installed

Install the missing runtime (.NET 5 Runtime in this case) and you're good to go.

Bozhidar Stoyneff
  • 3,576
  • 1
  • 18
  • 28
  • Can confirm that the same happened to me. After upgrading Visual Studio I was missing the out-of-support .Net 5 runtime. Installing it fixed the issue for me. Thanks! – Amir Mahdi Nassiri Oct 18 '22 at 19:34
2

Seems like your api is not not accessible and its returning error HTML page by default.

You can try below solution:-

I think you are using httpclient to get data to blazor application. If you have separate projects in solution for blazor and web api, currently your startup application may set to run blazor project only. Change startup projects to multiple (blazor and web api app) and give httpClient url in startup of blazor application, as webApi application url, that may solve your issue.

Ameerudheen.K
  • 657
  • 1
  • 11
  • 31
  • I am relatively new to Blazor and in my case I created a new page to edit "users" (not with the MS-Identity-framework, only a simple SQL-DB-table). I had TWO corrections to make. (1) I had to change the SQL-table-name from USER to USERS , AND, change all C# references (easy to do when renaming files) from "USER" to "USERS" since "user" is a reserved word within SQL-Server. (2) However, being new, I "overlooked" adding a UsersController.cs (I did add REPOSITORY (Server-project) and SERVICES (Client-project). After both corrections, the error no longer appeared. Thanks to @Ameenrudheen.K – John D Nov 19 '21 at 19:41
1

I got the same error. Red herring. use your browser or postman to check your api endpoint is returning the json data and not some HTML. In my case my "api/companytypes" had a typo.

private CompanyType[] companytypesarray;
private List<CompanyType> CompanyTypeList;
private List<CompanyType> CompanyTypeList2;
   
public async Task<bool> LoadCompanyTypes()
{
    //this works
    CompanyTypeList = await Http.GetFromJsonAsync<List<CompanyType>>("api/companytype");

    //this also works reading the json into an array first
    companytypesarray = await Http.GetFromJsonAsync<CompanyType[]>("api/companytype");
    CompanyTypeList2 = companytypesarray.ToList();

    return true;
}
dean veggy
  • 39
  • 4
  • 2
    Correct answer. The message is simply a red herring. Blazor does an outstanding job of bypassing breakpoints and swallowing error messages. Don't expect to be able to step through your code to find your problem. Isolate each line in a try block. Delete bin and obj folders. Rebuild. Restart your browser and clear the cache. Repeat till you find it or get too old to continue.. –  Apr 10 '21 at 20:57
  • thanks yes. true. frequent browser Cache deleting. css versioning, prolific try/except. and when debugging goes AWOL - delete those debug folders in BIN & OBJ. – dean veggy Apr 11 '21 at 22:44
1

I was having the same problem, "JsonReaderException: '<' is an invalid start of a value."

In my case the url for the REST service was wrong.

I was using the URL from the client project. Then I looked at the Swagger screen, https://localhost:44322/swagger/index.html and noticed the right URL should start with "44322"... Corrected, worked.

1

I know this is an old question, but I had the same problem. It took some searching, but I realized that the return data was in XML instead of JSON.

I'm assuming your "http" variable is of type HttpClient, so here's what I found worked for me.

By setting the "Accept" header to allow only JSON, you avoid a miscommunication between your app and the remote server.

http.DefaultRequestHeaders.Add("Accept", "application/json");
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
computercarguy
  • 2,173
  • 1
  • 13
  • 27
0

I had the same issue when passing in an empty string to a controller method. Creating a second controller method that doesn't accept any input variables, and just passing an empty string to the first method helped to fix my problem.

        [HttpGet]
        [ActionName("GetStuff")]
        public async Task<IEnumerable<MyModel>> GetStuff()
        {
            return await GetStuff("");
        }

        [HttpGet("{search}")]
        [ActionName("GetStuff")]
        public async Task<IEnumerable<MyModel>> GetStuff(string search)
        {
            ...
            
        }
0

Versions of package

Try to update your packages to old or new version. In my case, system.net.http.json is updated from 6.0 to 5.0

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 12 '21 at 15:02
0

Likely you are using an Asp.NetCore hosted WASM application. By default the client's App.razor has something similar to:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView DefaultLayout="@typeof(MainLayout)"
                                RouteData="@routeData">
                <NotAuthorized>
                    <RedirectToLogin />
                </NotAuthorized>
                <Authorizing>
                    <Loading Caption="Authorizing..."></Loading>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

Herein lies the problem. Since the Client and Server share the same base address, when the application cannot find "api/account/getstatesforprofile" it gives you the client's "Sorry, there's nothing at the address" page. Which is of course HTML.

I have not found the solution to this issue, but I am working on it and will reply once I find an issue.

Phillip
  • 94
  • 4
0

In my case, I had a comma (,) written mistakenly at the beginning of the appsettings.json file ... Just check your file and verify

/////// my error details ////// System.FormatException HResult=0x80131537 Message=Could not parse the JSON file. Source=Microsoft.Extensions.Configuration.Json StackTrace: at line 16 This exception was originally thrown at this call stack: [External Code] Inner Exception 1: JsonReaderException: ',' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0. ////

Nisais_N
  • 1
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 28 '22 at 12:58
0

For me, most of the time it is the @lauri-peltonen answer above. However, now and again, depending on who wrote the controller I have found that this will work in Swagger but not when you call it via the client (at least in this Blazor project we are on.)

[HttpGet]
[Route("prog-map-formulations")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
  ...
}

It sends the request as:

api/formulation-performance-program-map/analytical-assoc-values?formulationId=1

And I get results in Swagger but failes with the '<' OP error.

When I change ONLY the route to:

[HttpGet]
[Route("prog-map-formulations/{formulationId:int}")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
  ...
}

It sends the request as:

api/formulation-performance-program-map/analytical-assoc-values/1

And this works in both Swagger as well as from the Client side in Blazor.

Of course, once updated, I did have to clear the cache!

Grandizer
  • 2,819
  • 4
  • 46
  • 75
0

If you delete "obj" folder in your directory then clean the solution and rebbuild it the exception will be resolved

Yusuf
  • 1
0

It accurs when any of binded properties was null or empty

0

I am new to working with Blazor, but the reason I was getting this error was because I accidentally published the client instead of the server. Once I corrected this mistake and published the server, I had to change the 'Enable 32-Bit Applications' setting to True in the application pool in IIS. After making this adjustment, the application worked fine.

wdcocom
  • 1
  • 1
-1

In all these, there is two things that was my issue and realized, first off was that Route[("api/controller")] instead of Route[("api/[controller]")], that is missing square brackets. In the second exercise I was doing, with the first experience in mind, was from the name of the database. The database had a dot in the name (Stock.Inventory). When I change the database name to StockInventory it worked. The second one I am not so sure but it worked for me.

Bainn
  • 37
  • 12