如何请求匿名用户调用控制器?

How to request call to controller with anonymous user?

我正在使用带身份验证的 Blazor WebAssemlby。当我通过登录身份验证时,everythink 工作正常。但是当我没有登录(匿名)时,我想 post 向控制器之一请求(获取一些数据)但它不起作用。

如何为匿名用户使用国家控制器?

这是我的代码。

查看:

@page "/certificate"
@using SkupinaPrimera.Shared.Models
@using Microsoft.AspNetCore.Authorization
@inject HttpClient Http
@attribute [AllowAnonymous]

<h3>Claim your Certificate</h3>

@code {
private User user = new User();
List<Country> countries = new List<Country>();

[AllowAnonymous]
protected override void OnInitialized()
{
    GetCountries();
}

private async Task GetCountries() {  
    try
    {
       var result = await Http.GetFromJsonAsync<List<Country>>("Country");
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }
 }
}

控制器:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SkupinaPrimera.Shared.Models;

namespace SkupinaPrimera.Client.Pages
{
    [AllowAnonymous]
    [ApiController]
    [Route("Country")]
    public class CountryController : ControllerBase
    {
        // GET
        [AllowAnonymous]
        [HttpGet]
        public IEnumerable<Country> Get()
        {
            var cultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            var countries = new List<Country>();
            foreach (var info in cultureInfo)
            {
                if (!string.IsNullOrWhiteSpace(info.Name))
                {
                    var regionInfo = new RegionInfo(info.LCID);
                    if (countries.Count(x => x.Name == regionInfo.EnglishName) == 0)
                    {
                        countries.Add(new Country
                        {
                            Id = info.LCID,
                            Name = regionInfo.EnglishName
                        });
                    }
                }
            }

            return countries.OrderBy(x=>x.Name);
        }
    }
}

更新: 在网络中我可以看到这个电话。它有什么用?

https://localhost:44372/connect/authorize?client_id=Project.Client&redirect_uri=https%3A%2F%2Flocalhost%3A44372%2Fauthentication%2Flogin-callback&response_type=code&scope=Project.ServerAPI%20openid%20profile&state=ba2527a68ed4480497e48a68b390599b&code_challenge=dwd_kgszWFyWq2OrAMuedK26RfjOt4v2ieHEQ7W46l8&code_challenge_method=S256&prompt=none&response_mode=query

参见: https://docs.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/additional-scenarios?view=aspnetcore-3.1#unauthenticated-or-unauthorized-web-api-requests-in-an-app-with-a-secure-default-client

您需要在 program.cs 文件中添加这样的代码:

builder.Services.AddHttpClient("ServerAPI.NoAuthenticationClient", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));

然后这样消费:

@inject IHttpClientFactory ClientFactory

protected override async Task OnInitializedAsync()
{
    // Create a httpClient to use for non-authenticated calls
    NoAuthenticationClient =
         ClientFactory.CreateClient(
             "ServerAPI.NoAuthenticationClient");

    // Make the non-authenticated call
    await NoAuthenticationClient.PostAsJsonAsync(
            "SyncfusionHelpDesk", objHelpDeskTicket);
}