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



我正在使用带有身份验证的Blazor WebAssemlby。当我通过登录进行身份验证时,每个想法工作都正常。但是当我没有登录(匿名(时,我想向其中一个控制器发布请求(以获取一些数据(并且它不起作用。

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

这是我的代码。

视图:

@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://learn.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

您需要在程序.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);
}

相关内容

  • 没有找到相关文章

最新更新