Blazor类型转换错误:如何修改BlogPost.cs对接Django REST API?
解决Blazor对接Django REST API的类型转换问题
问题根源
你遇到的错误是因为Django API返回的Starter.PostModels.Post[]数组无法直接隐式转换为Blazor服务层需要的IEnumerable<Starter.UI.Services.BlogPost>——两者是完全独立的类,必须手动做类型映射才能完成转换。
修改与实现步骤
1. 对齐BlogPost类与API返回字段
先确认Django API返回的JSON数据结构,比如假设返回格式如下:
[ { "id": 1, "title": "Blazor对接Django指南", "content": "这是一篇测试文章", "created_at": "2024-05-20T14:30:00Z" } ]
修改Starter.UI.Services.BlogPost.cs,确保属性和API返回字段匹配,字段名不一致时用JsonPropertyName指定映射:
using System.Text.Json.Serialization; namespace Starter.UI.Services { public class BlogPost { [JsonPropertyName("id")] public int Id { get; set; } [JsonPropertyName("title")] public string Title { get; set; } = string.Empty; [JsonPropertyName("content")] public string Content { get; set; } = string.Empty; [JsonPropertyName("created_at")] public DateTime CreatedAt { get; set; } } }
2. 在服务中添加手动转换逻辑
在你的API服务类中,获取到Post[]后,逐个将Post对象转换为BlogPost对象:
public async Task<IEnumerable<BlogPost>> GetBlogPostsAsync() { var apiResponse = await _httpClient.GetFromJsonAsync<Starter.PostModels.Post[]>("api/posts/"); // 手动映射每个字段 return apiResponse.Select(post => new BlogPost { Id = post.Id, Title = post.Title, Content = post.Content, CreatedAt = post.CreatedAt }); }
3. 可选:用AutoMapper简化映射(多字段场景)
如果模型字段较多,可以用AutoMapper减少重复代码:
- 安装NuGet包:
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection - 在
Program.cs注册AutoMapper:builder.Services.AddAutoMapper(typeof(Program)); - 创建映射配置文件:
public class PostMappingProfile : Profile { public PostMappingProfile() { // 自动匹配同名同类型的属性 CreateMap<Starter.PostModels.Post, BlogPost>(); } } - 在服务中使用映射:
private readonly IMapper _mapper; public BlogService(HttpClient httpClient, IMapper mapper) { _httpClient = httpClient; _mapper = mapper; } public async Task<IEnumerable<BlogPost>> GetBlogPostsAsync() { var postsFromApi = await _httpClient.GetFromJsonAsync<Starter.PostModels.Post[]>("api/posts/"); return _mapper.Map<IEnumerable<BlogPost>>(postsFromApi); }
关键注意事项
- 确保两个模型的属性类型严格一致(比如Django的
DateTime对应C#的DateTime,字符串类型无差异) - 如果API返回的JSON字段名和C#属性名不同,必须通过
JsonPropertyName显式指定对应关系,否则会导致反序列化失败
内容的提问来源于stack exchange,提问作者Hamza Jamal
相关产品推荐
相关产品推荐

