You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搭建Blazor WASM+Strapi博客:如何解决前后端连接失败问题?

解决Blazor WASM与Strapi后端连接问题

核心配置修正

1. 修复Program.cs的配置绑定错误

你当前的ConfigureServices方法未被正确调用,且配置节点名称不匹配:

  • appsettings.json里的配置节点是AppSettings,但代码中错误使用了config.GetSection("App")
  • Blazor WASM的配置绑定应直接在Main方法内完成,无需单独定义ConfigureServices方法

修改后的Program.cs代码:

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using frontend.Models;

namespace frontend
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            // 绑定AppSettings配置
            var appSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
            builder.Services.AddSingleton(appSettings);

            // 配置HttpClient指向Strapi API地址
            builder.Services.AddScoped(sp => new HttpClient 
            { 
                BaseAddress = new Uri(appSettings.STRAPI_API_URL) 
            });

            await builder.Build().RunAsync();
        }
    }
}

2. 配置Strapi的CORS规则

Strapi默认会限制跨域请求,需在后台添加允许Blazor前端的规则:

  • 进入Strapi后台 → 设置 → 全局设置 → CORS
  • 将你的Blazor前端地址(如http://localhost:5000或https://localhost:5001)添加到允许的来源
  • 确保允许的方法包含GET, POST, PUT, DELETE,允许的头包含Content-Type, Authorization

3. 验证Strapi API可用性

直接在浏览器或Postman访问http://localhost:1337/api/[你的内容类型](比如内容类型为posts则访问http://localhost:1337/api/posts),确认能返回数据:

  • 检查Strapi是否正常运行在1337端口
  • 确认内容类型的权限中,public角色的find、findOne等权限已开启
  • 重启Strapi服务,确保strapi-plugin-transformer插件生效

连接测试示例

在Blazor组件中添加以下代码,验证能否获取Strapi数据:

@page "/test-strapi"
@inject HttpClient Http
@inject AppSettings AppSettings

<h3>测试Strapi连接</h3>

@if (posts == null)
{
    <p>加载中...</p>
}
else
{
    <ul>
        @foreach (var post in posts)
        {
            <li>@post.Title</li>
        }
    </ul>
}

@code {
    private List<Post> posts;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            posts = await Http.GetFromJsonAsync<List<Post>>("/api/posts");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    // 对应Strapi内容类型的数据结构
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        // 根据你的Strapi内容类型添加其他字段
    }
}

替代方案

如果问题仍存在,可尝试:

  • 基于Strapi的OpenAPI规范,用NSwag生成Blazor可用的API客户端代码
  • 改用GraphQL连接Strapi,通过GraphQL.Client库实现查询

内容的提问来源于stack exchange,提问作者Bromansibles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:31:24