【发布时间】:2020-07-03 09:43:00
【问题描述】:
我正在使用带有身份验证的 Blazor WebAssemlby。当我通过登录验证时,everythink 工作正常。但是当我没有登录(匿名)时,我想向其中一个控制器发布请求(以获取一些数据)并且它不起作用。
如何为匿名用户使用 Country 控制器?
这是我的代码。
查看:
@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
【问题讨论】:
-
AllowAnonymous 应该这样做。发生了什么?
-
它没有。它显示的视图,但在请求时它没有到达控制器。
-
您在浏览器的“网络”选项卡中看到什么响应代码?
标签: c# .net authorization blazor