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:
When access the API via Blazor server application, the request like this:
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:
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