Post upgrade issue SfDataManager with WebApiAdaptor

I've upgrade to the latest version as of now 18.4.0.30 from a 17. version in our evaluation project and now I'm receiving an error using the grid.  As soon as the grid tries to load data from the web API I get the following error.  It never actually calls the API at least it's not hitting my debug breakpoint on the beginning it seems the error is generated before then.  I've searched the forums and found some similar issues that don't seem to apply, but haven't found anything specific to this issue.  

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Syncfusion.Blazor.Data.WebApiAdaptor.ProcessResponse[T](Object data, DataManagerRequest queries)
   at Syncfusion.Blazor.DataManager.ExecuteQuery[T](DataManagerRequest queries)
   at Syncfusion.Blazor.DataManager.ExecuteQuery[T](Query query)
   at Syncfusion.Blazor.Grids.SfGrid`1.GenerateAndExecuteQuery(Query query, Boolean foreignKeyHandle, Boolean isForeignKeyAction, Int32 VirtualStartIndex, Int32 VirtualEndIndex, Boolean isQueryGenerated, Boolean preventForeign)
   at Syncfusion.Blazor.Grids.SfGrid`1.DataProcess(ActionArgs action, ActionEventArgs`1 actionArgs)


11 Replies 1 reply marked as answer

RS Renjith Singh Rajendran Syncfusion Team December 18, 2020 09:32 AM UTC

Hi Jonathan, 

Greetings from Syncfusion support. 

We tried reproduce the reported problem by creating a sample in our latest version 18.4.0.30 based on this scenario. But Grid renders fine with the sample from our side. We are attaching the sample for your reference, please download the sample from the link below, 
 
Kindly refer the above attached sample and if you are still facing difficulties then the following details would be helpful for us to proceed further. 

  1. Share the sample which you have tried from your side. This would be helpful for us to validate the problem based on your scenario.
  2. Or if possible reproduce the reported problem with the above attached sample and share with us for further analysis.
  3. Share the exact scenario or proper replication procedure.
  4. Share the video demo showing the replication of the problem you are facing
  5. Share the complete Grid rendering codes.

The provided information will help us analyze the problem, and provide you a solution as early as possible. 

Regards, 
Renjith Singh Rajendran 



JN Jonathan Nordell December 18, 2020 10:37 PM UTC

It has to have something to do with Azure authentication and authorization for the application.  If I turn off all authentication in the application it works.  As soon as I add back the Authorize attribute to the controller it breaks.  I can pull up the controller manually on a page and it returns a valid JSON result, but it won't work within the grid.


RS Renjith Singh Rajendran Syncfusion Team December 22, 2020 03:00 AM UTC

Hi Jonathan, 

We are not clear about the exact scenario you are facing this reported problem. We suggest you to ensure to return the data from WebApi service/controller as Items and Count pair to get data bind in Grid as explained in below documentation. 

The following details would be helpful for us to further validate this scenario and proceed further. 

  1. Share a simple issue reproducing sample for us to validate the problem based on your scenario.
  2. Or if possible reproduce the reported problem with the sample attached from our previous update and share with us for further analysis.
  3. Share the video demo showing the replication of the problem you are facing.
  4. Share the complete Grid rendering codes.
  5. Share the controller page codes and Startup.cs file.
  6. Share the browser network tab response details of your webapi service.

And also we suggest you to bind the “OnActionFailure” event to Grid. This event will be triggered for every failure in Grid. Please share the details you get in the “args” of this event handler for further analysis.  

The provided information will help us analyze the problem, and provide you a solution as early as possible. 

Regards, 
Renjith Singh Rajendran 



JN Jonathan Nordell December 22, 2020 09:09 PM UTC

I can provide some example code, but you would have to setup your own Azure tenant and application in order to do any testing.

The issue has something to do with changes to .NET 5.0 and authentication.  The application in startup has a policy which enforces RequireAuthenticatedUser.  The front end of the Blazor application works perfectly and I'm able to authenticate and retrieve claims.  Previously I used the AzureAD.UI packages for authentication and would add the .AspNetCore.AzureADCookie as a default header to the http client which was then passed with the WebAPI calls to the controller.  Now all that has changed and I haven't been able to figure out how to authenticate a user sessions and get a token returned using the new MS identity authentication packages. I've literally gone through probably 10 different examples provided by MS and other sites and none return the token to pass with the subsequent API calls.  Everything I've tried to retrieve the auth_token returns a null and every example I find regarding that issue points me to 3.1 or older code using the previous packages.

This all worked fine until I upgraded all the packages to the latest versions. I've seen a forum post listed that discussed adding a header to the DataManager, but I can't obtain the token to pass.


RS Renjith Singh Rajendran Syncfusion Team December 24, 2020 11:54 AM UTC

Hi Jonathan, 

We have analyzed your query. We could see that you are facing difficulties to authenticate a user sessions and get token returned using the new MS identity authentication packages. 

For this, you need to set authorization token in the httpclient header to make it. So we suggest you to get authorization token in MS identity by referring the below general documentation, 

You can find the below code in above documentation with which you can acquire access token, 

 
string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes); 


And also HttpClient must be provided with the authorization token if you want to use Authorization. Kindly refer the below code example to add authentication header to the global HttpClient object. 

Please use the below code example to add the authentication token, 

@using System.Net.Http.Headers@inject HttpClient Http
... 
 
@code{ 
   protected async override Task OnInitializedAsync() 
    { 
       Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer""{OAUTH TOKEN}");    //add authentication token, instead of highlighted
     } 
} 
 

Please get back to us if you need further assistance. 

Regards, 
Renjith Singh Rajendran 



JN Jonathan Nordell December 24, 2020 09:26 PM UTC

I've already tried all the example you linked too.  It's also not 100% applicable because I don't need to get the token from the controller.  The API itself works perfectly!!! 

After a bunch of searching through a lot of forums I found a way to get the token for the user.  In case anyone else reads this in _Host.cshtml the call is actually GetAccessTokenForUserAsync of ITokenAcquisition and you need to wrap it in a try/catch block.  This will trigger the exception first pass and then return a valid token on the second.  

@using Microsoft.Identity.Web
@inject MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler
@inject ITokenAcquisition tokenAcquisition;

        try
        {
            string[] scopes = new string[] { "user.read" };
            accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
        }
        catch (Exception ex)
        {
            ConsentHandler.HandleException(ex);
        }

I then added the statement "HeaderData.Add("Bearer", tokenProvider.AccessToken);" to OnInitialized in the page with the grid.  I did verify that the access token was injected properly and had a valid value for this.  I'm still getting the same error "Unexpected character encountered while parsing value: <. Path '', line 0, position 0.".  Something still isn't correct now in how the app is receiving the token for authentication.





RS Renjith Singh Rajendran Syncfusion Team December 30, 2020 03:19 AM UTC

Hi Jonathan, 

We suggest you to use custom message handler in your application and share the details you get in the browser console with us for further analysis.  
 
In the below attached sample, we have used custom message handler and Microsoft.JSInterop, we have send the request, response to Javascript function and write the request in browser console. Now, you can view the request in browser console. Please share with us these details you get in browser console for further analysis. 
 
Please find the below codes for using custom message handler in your application. We have added the below codes in above sample. 
 
[Startup.cs] 
 
public void ConfigureServices(IServiceCollection services){    services.AddRazorPages();    services.AddServerSideBlazor();    services.AddSingleton<WeatherForecastService>();    services.TryAddSingleton<IHttpContextAccessorHttpContextAccessor>();    services.AddScoped<HttpClient>(s =>    {        var ijs = s.GetService<IJSRuntime>();        var context = s.GetRequiredService<IHttpContextAccessor>();        var navManager = s.GetRequiredService<NavigationManager>();        Uri hostUri = null;        try        {            hostUri = new Uri(navManager.BaseUri);        }        catch (Exception)        {            ...        }        var cookieContainer = new CookieContainer();        HttpClient client = HttpClientFactory.Create(new MessageHandler1(ijs));   //crate client instance by using this way        client.BaseAddress = hostUri;        client.DefaultRequestHeaders.Add("Accept""application/json");        client.DefaultRequestHeaders.Add("Accept-Encoding""br, gzip, deflate");         if (context != null)        {            ...        }        return client;    });    services.AddSyncfusionBlazor();}//add this Custom message handlerpublic class MessageHandler1 : DelegatingHandler{    ...    protected async override Task<HttpResponseMessage> SendAsync(        HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)    {        var response = await base.SendAsync(request, cancellationToken);        ijs.InvokeAsync<HttpRequestMessage>("handleError"request);   //here we have send the request to js function and print the request in brower console        ijs.InvokeAsync<HttpRequestMessage>("Handleresponse"response);   //here we have send the response to js function and print the response in brower console        System.Threading.Interlocked.Increment(ref _count);        request.Headers.Add("X-Custom-Header", _count.ToString());        return await base.SendAsync(request, cancellationToken);    }}
 
 
Add a JavaScript file in wwwroot folder and add the below codes in that file. Also ensure to refer this JS file in your application. Find the below code  snippets. 
 
[debug.js] 
 
function handleError(request) { 
    console.log("Request Message : "); 
    console.log(request); 
} 
 
function Handleresponse(response) { 
    console.log("Response Message : "); 
    console.log(response); 
} 
 

And then refer the JavaScript file in _Host.cshtml file.  
 
[_Host.cshtml]<head>    ...    <link rel='nofollow' href="_content/Syncfusion.Blazor/styles/bootstrap4.css" rel="stylesheet" />    <script src="~/debug.js"></script></head>


Regards, 
Renjith Singh Rajendran 


Marked as answer

MA Martin June 19, 2023 03:41 PM UTC

Have you found a solution?


Just to clarify.  Both the poster here and I have found that using a DataGrid with sfDataManager using WebAPIAdaptor if the API is in the same project as the Blazor page from which it is called, and if using Azure AD  Authentication the API is not called.  Something fails before the API is entered, presumably something to do with authentication.


In my case I am using Syncfusion 21.2.10 with dot net 6





SP Sarveswaran Palani Syncfusion Team June 23, 2023 03:21 AM UTC

Hi Martin,

Greetings from Syncfusion support.

Before proceeding further with your requirement kindly share the below details to validate further at our end.


  1. Are you facing a same issue reported by an above customer?
  2. Facing any difficulties in initial data binding?
  3. Share code snippet or simple issue reproducible runnable sample to us.
  4. We would like to know more about the issue in detail. 


The above requested details will be helpful to validate further at our end and provide solution as earlier as possible.

Regards,
Sarvesh



MA Martin December 10, 2023 07:40 PM UTC

May I resurrect this issue please.


To demonstrate the problem simply add Azure (Entra) AD authentication to the sample referred to here: https://blazor.syncfusion.com/documentation/datagrid/entity-frame-work



PS Prathap Senthil Syncfusion Team December 12, 2023 02:18 AM UTC

Hi Martin,

Before proceeding with the reporting problem, we require some additional clarification from your end. Please share the below details to proceed further at our end.

  • Please provide us with a simple, reproducible sample of the issue with duplicate data.

  • could you please provide more details on how you have configured the authentication on your end?

  • Any specific settings or configurations you applied during the authentication setup. Or Any error messages or unexpected behaviors you encountered during the process.

  • If possible, a video demonstration of the problem would be greatly appreciated as it can help us identify the issue more effectively.

  • If possible, kindly share your attempt to replicate the issue using the attached simple sample.

Above-requested details will be very helpful in validating the reported query at our end and providing a solution as early as possible.


Regards,
Prathap S


Attachment: DatagridWithWebapiSample_9700dd57.zip

Loader.
Up arrow icon