Exception: '<' is an invalid start of a value - json

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?

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.

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.

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)

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.

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.

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:
Install the missing runtime (.NET 5 Runtime in this case) and you're good to go.

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;
}

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");

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

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

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.

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.

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.
////

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!

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

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.

Related

How to load angular-formly vm.fields object from remotely-generated json?

In my application I have dynamic field sets on what is otherwise the same form. I can load them from the server as javascript includes and that works OK.
However, it would be much better to be able to load them from a separate API.
$.getJSON() provides a good way to load the json but I have not found the right place to do this. Clearly it needs to be completed before the compile step begins.
I see there is a fieldTransform facility in formly. Could this be used to transform vm.fields from an empty object to whatever comes in from the API?
If so how would I do that?
Thx. Paul
There is an example on the website that does exactly what you're asking about. It uses $timeout to simulate an async operation to load the field configuration, but you could just as easily use angular's own $http to get the json from the server. It hides the form behind an ng-if and only shows the form when the fields return (when ng-if resolves to true, it compile the template).
Thx #kent
OK, so we need to replace the getFields() promise with this
function getFields() {
return $http.get('fields-demo.json', {headers:{'Cache-Control':'no-cache'}});
}
This returns data.fields so in vm.loadingData we say
vm.fields = result[0].data;
Seems to work for OK for me.
When testing I noticed that you have to make sure there is nothing wrong with your json such as using a field type you haven't defined. In that case the resulting error message is not very clear.
Furthermore you need to deal with the situation where the source of the data is unavailable. I tried this:
function getFields() {
console.log('getting',fields_url);
return $http.get(fields_url, {headers: {'Cache-Control':'no-cache'}}).
error(function() {
alert("can't get fields from server");
//return new Promise({status:'fields server access error'}); //??
});
.. which does at least throw the alert. However, I'm not sure how to replace the promise so as to propagate the error back to the caller.
Paul

JAX-WS adds namespace in Signature of token

I am accessing a third party web service using JAX-WS generated client (Java) code.
A call to a service that initiates a client session returns a Token in the response which, a.o., contains a Signature. The Token is required in subsequent calls to other services for authentication purposes.
I learned from using SoapUI that the WS/Endpoint requires the Token to be used as-is... meaning everything works fine when I literally copy the Token (which is one big line) from the initial response to whatever request I like to make next.
Now I am doing the same in my JAX-WS client. I retrieved a Token (I copied it from the response which I captured with Fiddler) and I tested it succesfully in a subsequent call using SoapUI.
However, when performing a subsequent call to a service using the JAX-WS client, the Signature part in the Token is changed. It should look like:
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">...</Signature>
But (when capturing the request with Fiddler) it now looks like:
<Signature:Signature xmlns:Signature="http://www.w3.org/2000/09/xmldsig#" xmlns="http://www.w3.org/2000/09/xmldsig#">...</Signature:Signature>
Apparently this is not acceptable according to the WS/Endpoint so now I'd like to know:
Why is the Token marshalled back this way?
More importantly, how can I prevent my client from doing that?
Thanks in advance!
Have you tested it? It should work nevertheless. The original signature used the defautl namespace (...xmldigsig) the JAXB version uses the same namespace but explicit says that the Signature element belongs to that namespae (Signature:Signature). The effect is the same, both xml express that Signature is in the http://www.w3.org/2000/09/xmldsig# namespace
You can customize the jaxby output with #XMLSchema on the package info, #XMLType on the class or inside the element.
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
By the help of #Zielu I was able to solve this by altering package-info.java (in the package of the generated files) like so:
#javax.xml.bind.annotation.XmlSchema(
namespace = "http://namespaceofthirdparty-asingeneratedversionof package-info.java"
, xmlns = {
#javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/2000/09/xmldsig#", prefix = "")
}
, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.where.generated.files.are;

Meteor: reading simple JSON file

I am trying to read a JSON file with Meteor. I've seen various answers on stackoverflow but cannot seem to get them to work. I have tried this one which basically says:
Create a file called private/test.json with the following contents:
[{"id":1,"text":"foo"},{"id":2,"text":"bar"}]
Read the file contents when the server starts (server/start.js):
Meteor.startup(function() {
console.log(JSON.parse(Assets.getText('test.json')));
});
However this seemingly very simple example does not log anything to the console. If I trye to store it in a variable instead on console.logging it and then displaying it client side I get
Uncaught ReferenceError: myjson is not defined
where myjson was the variable I stored it in. I have tried reading the JSON client side
Template.hello.events({
'click input': function () {
myjson = JSON.parse(Assets.getText("myfile.json"));
console.log("myjson")
});
}
Which results in:
Uncaught ReferenceError: Assets is not defined
If have tried all of the options described here: Importing a JSON file in Meteor with more or less the same outcome.
Hope someone can help me out
As per the docs, Assets.getText is only available on the server as it's designed to read data in the private directory, to which clients should not have access (thus the name).
If you want to deliver this information to the client, you have two options:
Use Assets.getText exactly as you have done, but inside a method on the server, and call this method from the client to return the results. This seems like the best option to me as you're rationing access to your data via the method, rather than making it completely public.
Put it in the public folder instead and use something like jQuery.getJSON() to read it. This isn't something I've ever done, so I can't provide any further advice, but it looks pretty straightforward.
The server method is OK, just remove the extra semi-colon(;). You need a little more in the client call. The JSON data comes from the callback.
Use this in your click event:
if (typeof console !== 'undefined'){
console.log("You're calling readit");
Meteor.call('readit',function(err,response){
console.log(response);
});
}
Meteor!

why adding razorformat breaks web services in servicestack latest 3.9.45.0

I am breaking my head today why after upgrading to latest servicestack and servicestack.razor my routing in web services stops working. So I did the following test.
created a new empty web project in vs.net 2012
added web.config file from rockstar
added servicestack and razor through nuget
added apphost and global.asa
in my configure() i did not add anything - no plugins.
added a simple echoservice with route specified
at this point point all works fine, i click the routed url and get my echo result back
added the line to config to add RazorFormat plugin
Now the route does not work, I am getting 404 (file not found) after return from the service with echo data. I can create a view for that service and then all fine, but what happened to default display?
Thanks
Mark
I tried to do the same with servicestack out of the box example and get the same result
Took a sample from servicestack – RootPath40 + Common and included them in separate solution
Compiled and it works
Current version of servicestack used by example is 3.9.11.0
Ran the following to update servicestack and install razor on both projects in the solution
so i get latest 3.9.45
install-package servicestack
install-package servicestack.razor
Tested – works fine!!!. I am testing specifically Hello service using the route Hello ->
localhost/RootPath40/hello
Added 1 line to Global.asax.cs – Configure function
public override void Configure(Container container)
{
container.Register(new TodoRepository());
**Plugins.Add(new RazorFormat());**
}
Now the route hello do not work anymore because I get error 404 not found.
I am using vs.net 2012 and windows 8
I am sure I am missing something very trivial, anyone knows...
Thanks
After struggling a little more I see that if I add reference to System.Web.Razor.Unofficial.dll then razor pages are served but routed web services stop working, the minute I remove the reference the web service routing urls are fine but razor pages are not served.
What am I missing?
Finally i figured out the problem.
The new version of servicestack (3.9.45.0) appears to have a bug in IF condition.
In HtmlFormat.cs
public void SerializeToStream(IRequestContext requestContext, object response, IHttpResponse httpRes)
{
var httpReq = requestContext.Get<IHttpRequest>();
if (httpReq != null && AppHost.ViewEngines.Any(x => x.ProcessRequest(httpReq, httpRes, response))) return;
...
...
The "NOT" ! (exclamation mark) is missing, but it should only return if none of the ViewEngines executed request. I added the NOT and walla, all works.
if (httpReq != null && **!**AppHost.ViewEngines.Any(x => x.ProcessRequest(httpReq, httpRes, response))) return;
Thanks
Mark
This was a bug with the new Razor support that was identified in this issue and fixed in v3.9.46+ of ServiceStack.Razor.

How to get HTTP status code in HTTPService fault handler

I am calling a server method through HTTPService from client side. The server is a RestFul web service and it might respond with one of many HTTP error codes (say, 400 for one error, 404 for another and 409 for yet another). I have been trying to find out the way to determine what was the exact error code sent by the server. I have walked teh entire object tree for the FaultEvent populated in my fault handler, but no where does it tell me the error code. Is this missing functionality in Flex?
My code looks like this:
The HTTP Service declaration:
<mx:HTTPService id="myServerCall" url="myService" method="GET"
resultFormat="e4x" result="myServerCallCallBack(event)" fault="faultHandler(event)">
<mx:request>
<action>myServerCall</action>
<docId>{m_sDocId}</docId>
</mx:request>
</mx:HTTPService>
My fault handler code is like so:
private function faultHandler(event : FaultEvent):void
{
Alert.show(event.statusCode.toString() + " / " + event.fault.message.toString());
}
I might be missing something here, but:
event.statusCode
gives me the status code of the HTTP response.
So I can successfully do something like this in my fault handler function:
public function handleFault(faultEvent:FaultEvent):void
{
if (faultEvent.statusCode == 401)
{
Alert.show("Your session is no longer valid.", "", Alert.OK, this, loginFunc);
}
else
{
Alert.show("Failed with error code: " + faultEvent.statusCode as String);
}
}
Looks like you are out of luck: http://fantastic.wordpress.com/2007/12/26/flex-is-not-friendly-to-rest/
You may have to use ExternalInterface to get this handled in JS and then communicated to Flex.
The Flash Player needs help from the browser to be able to access the HTTP status code; therefore, this is not available on all platforms. For me, it failed with Flash Player 10.3.183.11 and Firefox 3.6.26, but worked with IE 8 on Windows 7.
The Adobe help for the FaultEvent.statusCode property hints at this, but unfortunately doesn't go into details:
this property provides access to the HTTP response status code (if available), otherwise the value is 0
So, if you absolutely need the status code, bad luck; if it's just to generate a better or friendlier error message for some frequent error conditions, it may be sufficient.
as3httpclient as posted by Ross is friendly to Rest, and provides you with the HTTP status code, as long as you're developing for AIR and not a browser-based app.
I could not get as3httpclient to work from the browser, even when making requests to the same origin. There's documentation stating you need to set up a socket policy file server to get this to work. Not scalable for our uses so I setup a Proxy web service on the same host running the flex app.
I use HTTPService to make the call to the proxy web service, which forwards the request to the destination, and the proxy web service returns the http status code and message body back to the HTTPService in xml.
Try using this instead of HTTPService:
http://code.google.com/p/as3httpclient/