在 ASP.NET Core 托管的 Blazor 应用程序中匿名调用服务器

时间:2021-01-11 05:17:17

标签: asp.net-core asp.net-core-webapi blazor blazor-client-side blazor-webassembly

我使用 VS 中包含的模板创建了一个 Blazor Webassembly 应用程序,其中包含授权和 ASP.NET Core 托管选项,如下所示:

Create Blazor dialog

我希望能够在未经身份验证的情况下向服务器发出 http 请求。我通过注释掉 WeatherForecastController 属性(甚至添加了 [Authorize] 属性)更改了 [AllowAnonymous] 中的代码:

//[Authorize] CHANGED
[AllowAnonymous] //CHANGED
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

FetchData.razor 页面中,连同代码中指出的其他更改,我注释掉了 @attribute [Authorize]

@page "/fetchdata"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using StackOverflowAuthProblem.Shared
@*@attribute [Authorize]*@ @*CHANGED*@
@inject HttpClient Http

@*CHANGED Html removed for brevity*@

<div>Exception message: @exceptionMessage</div>

@code {
    private WeatherForecast[] forecasts;

    string exceptionMessage; //CHANGED

    protected override async Task OnInitializedAsync()
    {
        try
        {
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exceptionMessage = exception.Message; //CHANGED returns an empty string

            exceptionMessage = exception.ToString(); //CHANGED returns
                //Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessTokenNotAvailableException: '' at
                //Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler.SendAsync(HttpRequestMessage request,
                //CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(
                //    HttpRequestMessage request, CancellationToken cancellationToken)
                //at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request,
                //HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop,
                //CancellationToken cancellationToken) 
                //at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__9`1[[StackOverflowAuthProblem.Shared.WeatherForecast[],
                //StackOverflowAuthProblem.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
                //at StackOverflowAuthProblem.Client.Pages.FetchData.OnInitializedAsync()
                //in E:\StackOverflow\StackOverflowAuthProblem\StackOverflowAuthProblem\Client\Pages\FetchData.razor:line 53

            //exception.Redirect(); CHANGE
        }
    }
}

我得到的异常在上面的代码中。我怀疑问题出在 App.razor 页面上,但无法弄清楚。

有什么帮助吗?

0 个答案:

没有答案