services.AddGrpcClient<UserFinder.UserFinderClient>(options => { options.Address = new Uri(configuration.GetValue<string>("GrpcUrls:UserFind")); }).ConfigureHttpClient((service, client) => { var http = service.GetService<IHttpContextAccessor>(); var token = ""; var has = http?.HttpContext?.Request?.Headers?.TryGetValue("Authorization", out var tokens); if (has.HasValue) { token = tokens.First().Remove(0, 7); } client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); });
本例是服务端 调用 Grpc service ,也就是webapi 服务端 调用 grpc 服务,因为 webapi 中存在 token , 所以直接在 request -> headers 中取 Authorization 的值 去掉 Bearer空格 7个字符 得到token
public class UserFindService { private readonly UserFinder.UserFinderClient _client; public UserFindService(UserFinder.UserFinderClient client, IHttpContextAccessor httpContextAccessor) { _client = client; CancellationToken = httpContextAccessor?.HttpContext?.RequestAborted ?? default; } protected CancellationToken CancellationToken { get; } public UserDataViewModel FindUser(string userid) { var user = _client.FindUser(request: new UserRequest { UserId = userid }, cancellationToken: CancellationToken); if (user == null) return null; return new UserDataViewModel { UserId = user.UserId, UserName = user.UserName, AvatarUrl = user.AvatarUrl, NickName = user.NickName, PhoneNumber = user.PhoneNumber, RealName = user.RealName, Email = user.Email, Gender = user.Gender, Country = user.Country, Province = user.Province, City = user.City, Authenticated = user.Authenticated }; } }