【问题标题】:Make anonymous call to Server in ASP.NET Core hosted Blazor App在 ASP.NET Core 托管的 Blazor 应用程序中对服务器进行匿名调用
【发布时间】:2021-04-16 02:07:49
【问题描述】:

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

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

//[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 页面上,但无法弄清楚。

有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

    有人在此处发布然后删除了一个答案,该答案说问题出在客户端项目的Program.cs 文件中的以下行:

    builder.Services.AddHttpClient("RclConsumer.ServerAPI", client => client.BaseAddress = new 
       Uri(builder.HostEnvironment.BaseAddress))
       .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
    

    我肯定遗漏了一些东西,否则我不禁会认为这是一个重大疏忽,即未经身份验证就无法访问 API 端点。

    public static class HttpClientService
    {
        public static HttpClient AnonymousHttpClient { get; set; }
    
        static HttpClientService()
        {
            AnonymousHttpClient = new HttpClient();
    
    #if DEBUG
            AnonymousHttpClient.BaseAddress = new Uri("https://localhost:44395/");
    #else
            throw new Exception("Need the Base address here");
    #endif
    
        }
    }
    

    我将其放入它自己的类库的原因是我计划添加 Razor 类库,并且我希望 HttpClient 的单个实例在整个解决方案中使用,因为 problem with sockets

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 2023-01-19
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多