I edited my answer to make it easier to understand, here is the code of blazor application:
private const string ServiceEndpoint = "https://localhost:7069/WeatherForecast";
private string a = "init";
private HttpResponseMessage res;
protected override async Task OnInitializedAsync() => await GetTodoItems();
private async Task GetTodoItems(){
try
{
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("Get"),
RequestUri = new Uri(ServiceEndpoint),
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
if (responseStatusCode == HttpStatusCode.Unauthorized)
{
a = "1";
}
else if (response.IsSuccessStatusCode)
{
a = "2";
}
else if (responseStatusCode == HttpStatusCode.InternalServerError)
{
a = "4";
}
else
{
a = "3";
}
} catch (Exception e)
{
a = "5";
}
}
So the usage of these codes is checking if it successfully catches the target status code from the API, it will run into the target loop and test to see if it will run into the exception. Here is my test result screenshot:
You can see from the screenshot, I made several breakpoints to test it and blazor application successfully caught the status code, then it run into the target loop. So it can work too about the status code 401. Know we continue running the program to check whether it will go to the exception:
You can see from the screenshot, it didn't go into exception.
-
Update:
I have checked the sample you uploaded, I made two changes and it works:
Step A:
Change the code in Program.cs file of API Project:
app.UseCors(cors => cors
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
before the app.UseAuthorization();
Step B:
I checked the sample, which seems it didn't add the 'if' loop code. The loop is the key to catch the 401 status code, you can do the next step when catch the 401 status code. For example, here is the code I added to the blazor client:
try{
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("Get"),
RequestUri = new Uri("https://localhost:7291/WeatherForecast"),
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
if (responseStatusCode == HttpStatusCode.Unauthorized)
{
a = "Permission Denied";
}
else if (response.IsSuccessStatusCode)
{
a = "2";
}
else if (responseStatusCode == HttpStatusCode.InternalServerError)
{
a = "4";
}
else
{
a = "3";
}
}
catch (Exception ex)
{
throw;
}
According to the loop code I added, if it successfully catch the 401 status code, it will show the access denied message. I added a breakpoint to test it and here is my test result:
You can see it successfully enter the loop, you can change the code to the action you want. In that case, blazor will not enter the exception.
Here is the blazor web site of the testing result:
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".
Best regards,
Xiaotian