我已经开始了一个新的Blazor项目与新的.NET 8自动设置.
我正try 在我的服务器项目中放置一个Web API控制器,并使用我的ASP.NET身份验证功能来验证某人是否已登录等.
以下是我的API控制器设置:
[Route("api/[controller]")]
public class TestDataController : ApiController
{
private readonly IWebHostEnvironment environment;
public TestDataController(IWebHostEnvironment environment)
{
this.environment = environment;
}
[HttpGet]
public IHttpActionResult Get()
{
string path = Path.Combine(environment.WebRootPath);
string returnData = $"filename: {"1"} | path: {path}";
return Ok(returnData);
}
}
然后,在我的客户端项目中,我有这样的设置:
Program.cs
个客户项目:
builder.Services.AddHttpClient("WebAPI",
client => client.BaseAddress = new Uri(builder.Configuration["BaseAddress"]));
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("WebAPI"));
剃须刀.
@page "/api-call"
@using App.Client.Services
@using System.Net.Http.Headers
@using Syncfusion.Blazor.Buttons
@using System.Text.Json
@inject IHttpClientFactory HttpClientFactory
@inject CookieService CookieService
@rendermode InteractiveWebAssembly
<h3>ApiCall</h3>
<SfButton OnClick="onToggleClick" Content="Click Me"></SfButton>
@if (APIValue != null)
{
<h3>@APIValue</h3>
}
else
{
<span>
Loading products...
</span>
}
@code {
private string APIValue { get; set; }
protected override async Task OnInitializedAsync()
{
}
private async Task onToggleClick()
{
var httpClient = HttpClientFactory.CreateClient("WebAPI");
//var cookie = await CookieService.GetCookieValue("YourCookieName");
// httpClient.DefaultRequestHeaders.Authorization =
// new AuthenticationHeaderValue("Bearer", cookie);
try
{
APIValue = await httpClient.GetFromJsonAsync<string>("TestData");
}
catch (HttpRequestException ex) // Non success
{
Console.WriteLine("An error occurred.");
APIValue = $"error {ex.Message}";
}
catch (NotSupportedException) // When content type is not valid
{
Console.WriteLine("The content type is not supported.");
}
catch (JsonException) // Invalid JSON
{
Console.WriteLine("Invalid JSON.");
}
}
}
我一直看到错误:
未找到网址为:https://localhost:44309/api/testdata的网页
我错过了什么让它工作吗?
我还没有控制器上的授权属性,因为我只是要在没有登录的情况下首先测试它.
谢谢