Blazor Wasm Asp.net Core hosted WebApi not consumed by Blazor Server

Prathamesh Shende 441 Reputation points
2023-08-02T12:07:13.31+00:00

Hi,
I have two project one is Blazor wasm with asp.net core hosted and another is blazor server.
Blazor wasm asp.net core webapi is public and I am consuming those into blazor Server project.
From last 7 days it's not consumed by blazor server project.

I test in local machine it working fine. After publish to server the blazor server project throwing 500 error.

another thing, if Blazor Wasm project consume this api then it's working correct. So I want to ask there any issue or setting that changed to consume api in blazor server from blazor wasm asp.net core hosted?

getting this error
It's not a cors error.

[2023-08-02 17:43:19.285 +05:30  EROR]
 HTTP GET / responded 500 in 470.0784 ms
System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Server Error).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsyncCore[T](Task`1 taskResponse, JsonSerializerOptions options, CancellationToken cancellationToken)
   at InnovusServer.Services.WorksService.Get() in D:\Projects\Innovus\Services\WorksService.cs:line 18
   at InnovusServer.Pages.Index.OnInitializedAsync() in D:\Projects\Innovus\Pages\Index.razor:line 333
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.HandleExceptionViaErrorBoundary(Exception error, ComponentState errorSourceOrNull)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.<WaitForQuiescence>g__ProcessAsynchronousWork|48_0()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.WaitForQuiescence()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(Int32 componentId, ParameterView initialParameters)
   at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<>c__11`1.<<InvokeAsync>b__11_0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, Object parameters)
   at Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
   at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count)
   at InnovusServer.Pages.Pages__Host.ExecuteAsync() in D:\Projects\Innovus\Pages\_Host.cshtml:line 8
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|28_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
Developer technologies | .NET | Blazor
{count} votes

Accepted answer
  1. Anonymous
    2023-08-03T07:06:54.2566667+00:00

    Hi @Prathamesh Shende

    About the 500 error in Blazor server application, if we use Fiddler to check request, we can see that:

    when access the API from the Blazor WebAssemably or directly access it from browser/postman, the request as below:

    success

    When access the API via Blazor server application, the request like this:

    User's image

    From the above screenshot, we can see that when send request from Blazor Server, the request header almost empty, no User-Agent and so on. So, it will return 500 error.

    To solve this problem, you can add the request header by yourself. refer to the following code:

    In the _Host.cshtml page, add the following script to get the user agent:

        <script>
            window.getUserAgent = () => {
                return navigator.userAgent;
            };
        </script>
    

    Index.razor:

    @page "/"
    @inject HttpClient _httpClient
    @inject IJSRuntime JS
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <SurveyPrompt Title="How is Blazor working for you?" />
    @if (works?.Any() == true)
    {
        @foreach (var item in works)
        {
            <div>@item.ID<br />@item.Name<br />@item.Title</div>
        }
    }
    @code {
        public class Work
        {
            public int ID { get; set; } 
            public string? Name { get; set; } 
            public string? Title { get; set; }
        }
        //public async ValueTask<List<Work>?> Get() =>
        //    await _httpClient.GetFromJsonAsync<List<Work>>($"https://cms.innovustech.in/api/works");
        public async ValueTask<List<Work>?> Get()
        {
            // var 
            _httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
            _httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
    
            if (string.IsNullOrEmpty(remoteUserAgent))
            {
                _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36");  //you can replace it to yours.
    
            }
            else
            {
                 _httpClient.DefaultRequestHeaders.Add("User-Agent", remoteUserAgent);
            } 
            var response = await _httpClient.GetAsync($"https://cms.innovustech.in/api/works"); 
            string json = await response.Content.ReadAsStringAsync(); 
    
            List<Work> items = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Work>>(json);
    
            return await Task.FromResult<List<Work>>(items);
    
        }
        List<Work>? works = new();
        private string remoteUserAgent ="";
        protected override async Task OnInitializedAsync()
        { 
            works = await Get(); //show error here that I mentioned before
        }
    
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                remoteUserAgent = await JS.InvokeAsync<string>("getUserAgent");
                StateHasChanged();
            }
        }
    }
    

    The output as below:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-08-02T16:10:38.9266667+00:00

    the server code is getting a 500 error. most likely the payload or url is invalid. maybe a header is wrong. you should log the response html so you can debug. also the service called should log the error. I use request guids, so in the errorlogs, I can match the failing call to the failing service request.

    An important part of building a system is adequate error logging, so production errors can be diagnosed.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.