網站首頁 編程語言 正文
以下文章來源于公眾號: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 集成越來越好,是得需要大家花費精力好好學習。
相關推薦
- 2022-05-15 jquery事件綁定方法介紹_jquery
- 2022-10-08 ASP.NET?MVC在基控制器中處理Session_實用技巧
- 2022-12-22 關于Python?ImportError:?No?module?named?通用解決方法_pytho
- 2023-04-03 Input系統截斷策略的分析與應用詳解_Android
- 2022-07-24 Python使用apscheduler模塊設置定時任務的實現_python
- 2022-11-17 Android文本與視圖基本操作梳理介紹_Android
- 2022-09-22 在容器內獲取 Pod 信息
- 2022-09-01 C++中的Z字形變換問題_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支