我遇到了麻烦,我感谢的是路由问题。我已将控制器添加到 .NET 7 Blazor Server 应用程序,但无法使路由正常工作。我正在发布我的代码的样子。
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private static List<Product> Products = new List<Product>
{
new Product { Id = 1, Title = "Die Cut", Description="Die Cut Sticker Cut around the outer edege of the design.",Image="./Images/DieCut.jpg", Price= 2.99m },
new Product { Id = 2, Title = "Circle Cut", Description="Round Sticker With Your Design In The Center.",Image="./Images/OvalCut.jpg", Price= 2.99m },
new Product { Id = 3, Title = "Square Cut", Description="Square Sticker With Your Design In The Center.",Image="./Images/SquareCut.jpg", Price= 3.99m },
new Product { Id = 4, Title = "Oval Cut", Description="Oval Sticker With Your Design In The Center.",Image="./Images/OvalCut.jpg", Price= 4.99m },
new Product { Id = 5, Title = "Clear Back", Description="Die Cut Sticker Cut Around The Outer Edege Of The Design On Clear Material.",Image="./Images/ClearDieCut.jpg", Price= 5.99m },
new Product { Id = 5, Title = "Glow In The Dark", Description="Any Cut Type On Glow In The Dark Material.",Image="./Images/GlowInDark.jpg", Price= 6.99m },
};
[HttpGet]
public async Task<IActionResult> GetProducts()
{
return Ok(Products);
}
}
如果我这样调用控制器:
protected override async Task OnInitializedAsync()
{
var result = await Http.GetFromJsonAsync<List<Product>>("api/Product");
if (result != null)
{
Products = result;
}
}
我收到此错误:
InvalidOperationException:提供了无效的请求 URI。请求 URI 必须是绝对 URI,或者必须设置 BaseAddress。
如果我在这样的方法中设置完整的 Http 链接,它就可以工作:
private static List<Product> Products = new List<Product>();
protected override async Task OnInitializedAsync()
{
var result = await Http.GetFromJsonAsync<List<Product>>("https://localhost:7157/api/Product");
if (result != null)
{
Products = result;
}
}
这是路由问题吗?如果是,我该如何解决?
谢谢 布莱恩
由于您可以使用绝对 URL 访问 api,所以这不是路由问题。
如果你想在 blazor 组件中使用 httpclient 时省略基址,可以尝试:
在program.cs中:
var uri = builder.Configuration.GetValue<string>("HttpClientBaseUri");
builder.Services.AddHttpClient("", op =>
{
op.BaseAddress = new Uri(uri);
});
在 appsettings.json 中:
"HttpClientBaseUri": "your target uri"
在 Blazor 组件中:
@inject IHttpClientFactory httpclientfactory
.....
var client = httpclientfactory.CreateClient("apiclient");
var result = await client.GetFromJsonAsync<List<Product>>("api/Product");