【发布时间】:2020-07-11 13:21:45
【问题描述】:
我有一个包含以下详细信息的 proto 文件:
TestGRPC.proto:
syntax = "proto3";
option csharp_namespace = "MyGRPC";
package MyApi;
service Author {
rpc GetArticles (ArticleRequest) returns (ArticleResponse);
}
message ArticleRequest {
int32 articleId = 1;
int32 countryId = 2;
string userCookieId = 3;
}
message ArticleResponse {
int32 ArticleId = 1;
string Title = 2;
repeated TaxTagsResponse RelatedTaxTags = 3;
}
message TaxTagsResponse{
int32 TaxTagId = 1;
string DisplayName = 2;
}
这用于具有以下结构的 DTO 类的 asp.net core 3.1 gRPC 客户端项目:
public class ArticleDTO
{
public int ArticleId
{
get;
set;
}
public List<TaxTagsDTO> RelatedTaxTags
{
get;
set;
}
}
public class TaxTagsDTO
{
public int? TaxTagId
{
get;
set;
}
public int? ParentTagId
{
get;
set;
}
public int? CountryId
{
get;
set;
}
[JsonProperty("displayname")]
[RegularExpression(Constants.GeneralStringRegularExpression)]
public string DisplayName
{
get;
set;
}
public int? LanguageId
{
get;
set;
}
public List<CountryDTO> RelatedCountries
{
get;
set;
}
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ArticleResponse, ArticleDTO>().ForMember(dest => dest.RelatedTaxTags, opt => opt.MapFrom(src => src.RelatedTaxTags));
}
}
public class ArticleService : IArticleService
{
private readonly IOptions<UrlsConfig> _appSettings;
private readonly HttpClient _httpClient;
private readonly ILogger<ArticleService> _logger;
private readonly IMapper _mapper;
public ArticleService(HttpClient httpClient, IOptions<UrlsConfig> appSettings, ILogger<ArticleService> logger, IMapper mapper)
{
_appSettings = appSettings;
_httpClient = httpClient;
_logger = logger;
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
public async Task<ArticleDTO> GetArticleAsync(int articleId, int countryId, string userCookieId)
{
return await GrpcCallerService.CallService(_appSettings.Value.GrpcAuthor, async channel =>
{
var client = new AuthorGRPC.Author.AuthorClient(channel);
var response = await client.GetArticlesAsync(new ArticleRequest{ArticleId = articleId, CountryId = countryId, UserCookieId = userCookieId});
_logger.LogDebug("grpc response {@response}", response);
var articleResponse = _mapper.Map<ArticleDTO>(response);
return articleResponse;
});
}
}
任何人都可以通过提供解决此问题的指导来帮助我。
【问题讨论】:
-
注意:如果你使用 protobuf-net.Grpc,你就不需要使用 protoc 生成的类型 - 它直接在代码上工作- 第一个 POCO;您不需要需要使用任何工具,但是如果您想知道使用 protobuf-net.Grpc 会是什么样子:将您的 .proto 放在这里:protogen.marcgravell.com(强调:它可以完全使用您的手写类型,只要您通过属性告诉它数字)
-
感谢@MarcGravell 的回复。你能帮我一些代码示例作为我的问题的上下文参考吗
-
不清楚你到底想让我说明什么,只是将原型模式放入我提到的生成器中并不清楚
标签: c# automapper asp.net-core-3.1 c#-8.0 grpc-dotnet