目录一、咨询区Dmitriy二、回答区valentasm三、点评区以下文章来源于公众号:DotNetCore实战
一、咨询区
Dmitriy在 ASP.NET Core 中使用GRPC.ASPNETCore 工具包写 gRPC 服务,想实现 gRPC 的异常全局拦截,
代码如下:app.UseExceptionHandler(configure =>
{
configure.Run(async e =>
{
Console.WriteLine("Exception test code");
});
});
然后注入到 ServiceCollection 容器中:services.AddMvc(options =>
{
options.Filters.Add(typeof(BaseExceptionFilter));
});
奇怪的是,这段代码并不能实现拦截功能,我是真的不想让 try-catch 包裹所有的办法,太痛苦了。
二、回答区
valentasm我们可以给 gRPC 添加一个自定义拦截器,先看一下类定义:`using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Grpc.Core;using Grpc.Core.Interceptors;using Microsoft.Extensions.Logging;
namespace Systemx.WebService.Services{ public class ServerLoggerInterceptor : Interceptor { private readonly ILogger<ServerLoggerInterceptor> _logger;
public ServerLoggerInterceptor(ILogger<ServerLoggerInterceptor> logger)
{
_logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
//LogCall<TRequest, TResponse>(MethodType.Unary, context);
try
{
return await continuation(request, context);
}
catch (Exception ex)
{
// Note: The gRPC framework also logs exceptions thrown by handlers to .NET Core logging.
_logger.LogError(ex, $"Error thrown by {context.Method}.");
throw;
}
}
}
}接下来就可以在 Startup 中通过 AddGrpc 注入啦:
services.AddGrpc(options =>{ { options.Interceptors.Add<ServerLoggerInterceptor>(); options.EnableDetailedErrors = true; }});`三、点评区grpc 早已经替代 wcf 成功一种基于tcp的跨机器通讯技术,看得出 grpc 和 asp.net core 集成越来越好,是得需要大家花费精力好好学习。
相关推荐
© 2020 asciim码
人生就是一场修行