My First Call is being established and getting the data from the server while my second custom localhost call is being rejected by using Http.GetFromJsonAsync

mehmood tekfirst 771 Reputation points
2022-05-31T14:36:41.93+00:00

Hi,

I am trying to add custom component using razor.component and use in razor.view (in Asp.Net MVC Core 6).

My First Call is being established and getting the data from the server while my second custom localhost call is being rejected.
May be due to missing base address .

Why My second call is being missed ?

await Http.GetFromJsonAsync<Inquiry[]?>
        ("https://localhost:7177/api/Rent/franchises/?Code=" + postCodeOrTown + "&lattitude=" + providedLattitude + "&longitude=" + providedLongitude);

I added following in Program.cs

builder.Services.AddServerSideBlazor();

builder.Services.AddHttpClient();

Following is my code :

@using System.Net.Http
@using System.Net.Http.Json
@using System.Threading.Tasks
@inject HttpClient Http

<div>


                <input
                    type="text"
                    id="TxtBxPickUpLoc"
                    class="postcode tf-form-control"
                    placeholder="Please Enter Code"                                      
                   value="@inputValue"
                   @onchange="DoLocation"
                    autoComplete="off"
                />
                            @if(!string.IsNullOrWhiteSpace(inputValue))
                            {
                                <a className="location" href="#" id="branch-selector" onClick={onClearLocations}></a>
                            }
                            else if (string.IsNullOrWhiteSpace(inputValue))
                            {
                                <a className="location empty" href="#" id="branch-selector" onClick={onClearLocations}></a>
                            }

        </div>
        <div class="sautocomplete-content-container tk-search-drop-wrapper ac-drop-active">
            <div class="sautocomplete-content tk-search-drop">
                <div class="branch-info">                          
                    <ul id="LocationSuggestions" class="suggestions">
                        @if (locationData != null && locationData.Count() > 0)
                        {
                            @foreach (FranchiseWebInquiry suggestion in locationData!)
                            {
                                // Flag the active suggestion with a class
                                if (index == activeSuggestionIndex)
                                {
                                    className = "suggestion-active";
                                }
                                <li class="@className" key="@index + @suggestion.FranchiseName" onClick="onClick(suggestion)">
                                    <a pickupid="@suggestion.PickupId + @suggestion.FranchisesId"  franchisesid="@suggestion.FranchisesId" subofficeid="@suggestion.SubOfficeId" href="#">
                                        <span class="locName">@suggestion.FranchiseName</span>
                                        <span class="locDetails">@getAddress(suggestion)                                            
                                        </span>
                                    </a>
                                </li>
                                ++index;
                            }  

                             }            

                    </ul>                              
                </div>
            </div>
</div>


@code {
    private string inputValue = "";
    private string className = "";
    private int activeSuggestionIndex;
    private int index = 0;  
    private FranchiseWebInquiry[]? locationData;
    private bool getError;
    private bool shouldRender;

    protected override bool ShouldRender() => shouldRender;
    private GoogleGeocode? currentMapItems;  

    private async Task<GoogleGeocode?> loadGoogleGeoCodeData(string postCodeOrTown)
    {
        currentMapItems = await Http.GetFromJsonAsync<GoogleGeocode?>
        ("https://maps.googleapis.com/maps/api/geocode/json?types=geocode&language=en&key=mykey&address=" + postCodeOrTown);
        return currentMapItems;
    }

    private async Task getLocationsApi(string postCodeOrTown)
    {
        await loadGoogleGeoCodeData(postCodeOrTown);
        Result? serviceResult = currentMapItems!.Results!.FirstOrDefault();
        Location? locDetail = serviceResult != null && serviceResult.Geometry != null ? serviceResult.Geometry.Location:null;
        double providedLattitude = locDetail != null ? locDetail.Lat : 0;
        double providedLongitude = locDetail != null ? locDetail.Lng : 0;
        locationData = await Http.GetFromJsonAsync<FranchiseWebInquiry[]?>
        ("https://localhost:7177/api/Rent/franchises/?Code=" + postCodeOrTown + "&lattitude=" + providedLattitude + "&longitude=" + providedLongitude);
    }

    private async void DoLocation(ChangeEventArgs e)
    {
        inputValue = e.Value!.ToString();
        if (inputValue!.Length >= 5)
        {
           await getLocationsApi(inputValue);         
        }
        Console.WriteLine("It is definitely: " + inputValue);
    }    

    private string getAddress(FranchiseWebInquiry suggestion)
    {
        //debugger;
       string localAddress = "";
       if(suggestion != null){
          if(!string.IsNullOrWhiteSpace(suggestion.Address1)){
                localAddress =  suggestion.Address1 + " , ";
           }                  
           if(!string.IsNullOrWhiteSpace(suggestion.Address2)){
                localAddress += suggestion.Address2 + " , ";
           }
           if(!string.IsNullOrWhiteSpace(suggestion.Address3)){
                localAddress += suggestion.Address3 + " , ";
           } 
           if(!string.IsNullOrWhiteSpace(suggestion.Town)){
                localAddress += suggestion.Town + "- " + (!string.IsNullOrWhiteSpace(suggestion.PostCode) ? "(" + suggestion.PostCode + "), ":"");
           }
           if(!string.IsNullOrWhiteSpace(suggestion.PrimaryContact))
           {
                localAddress += suggestion.PrimaryContact;
           }           
        }
         return localAddress;  
    }

     }  

I want to create another razor.componet which is being replaced by following (and 'll change on every keystroke in textbox TxtBxPickUpLoc)

@if (locationData != null && locationData.Count() > 0)
                            {
                                @foreach (FranchiseWebInquiry suggestion in locationData!)
                                {
                                    // Flag the active suggestion with a class
                                    if (index == activeSuggestionIndex)
                                    {
                                        className = "suggestion-active";
                                    }
                                    <li class="@className" key="@index + @suggestion.FranchiseName" onClick="onClick(suggestion)">
                                        <a pickupid="@suggestion.PickupId + @suggestion.FranchisesId"  franchisesid="@suggestion.FranchisesId" subofficeid="@suggestion.SubOfficeId" href="#">
                                            <span class="locName">@suggestion.FranchiseName</span>
                                            <span class="locDetails">@getAddress(suggestion)                                            
                                            </span>
                                        </a>
                                    </li>
                                    ++index;
                                }  

                                 } 

This in my index.cshtml

   <div class="card">   
                                         @(await Html.RenderComponentAsync<RentWidget.Views.Shared.Components.AutoCompleteComponent>
                                             (RenderMode.ServerPrerendered/*,new {  Data="I came from Index",style= "badge-danger" }*/))  
                                 </div>

If I write with https://localhost:port/api then it works otherwise not.

In the above post,

I need to create and call/refresh a child razor.component on the call of DoLocation.

How can I call a child razor.component within a razor.component ?

My second question is to add baseAddress with all my localhost api calls.

for example:

 builder.Services.AddScoped(sp =>
        new HttpClient
        {
            BaseAddress = new Uri("https://localhost:7177")
        });

and my third question is :
Is there any problem by using both below :

builder.Services.AddServerSideBlazor();

 builder.Services.AddHttpClient();
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,190 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,581 Reputation points
    2022-05-31T15:16:18.633+00:00

    Set a breakpoint on the DoLocation function's first line. Then run your code. If it hits the breakpoint then step through the code (F10) and confirm it is calling the method you expect. If it doesn't hit the breakpoint then whatever condition you set up to trigger that call isn't being hit. You'll need to verify the method is properly wired up to be called.

    1 person found this answer helpful.