匿名调用ASP.NET Core Hosted Blazor应用程序中的服务器 [英] Make anonymous call to Server in ASP.NET Core hosted Blazor App
本文介绍了匿名调用ASP.NET Core Hosted Blazor应用程序中的服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在VS with Authorization and ASP.NET Core Hosted Options中使用包含的模板创建了Blazor WebAssembly应用程序,如下所示:
我希望无需经过身份验证即可向服务器发出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:StackOverflowStackOverflowAuthProblemStackOverflowAuthProblemClientPagesFetchData.razor:line 53
//exception.Redirect(); CHANGE
}
}
}
我得到的异常在上面的代码中。我怀疑问题出在App.razor
页中,但找不到答案。
有帮助吗?
推荐答案
有人在此处发布然后删除了一个答案,该答案称问题在客户端项目的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
这篇关于匿名调用ASP.NET Core Hosted Blazor应用程序中的服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文