我遇到了麻烦,我感谢的是路由问题。我已将控制器添加到 .net 7 blazor 应用程序,但无法使路由正常工作。我正在发布我的代码的样子。
[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: An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.
如果我在像 tihs 这样的方法中设置完整的 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中:
builder.Services.AddHttpClient("apiclient", op =>
{
op.BaseAddress = new Uri("https://localhost:7157");
});
在 Blazor 组件中:
@inject IHttpClientFactory httpclientfactory
.....
var client = httpclientfactory.CreateClient("apiclient");
var result = await client.GetFromJsonAsync<List<Product>>("api/Product");