目录一、咨询区Dmitriy二、回答区valentasm三、点评区以下文章来源于公众号:DotNetCore实战 一、咨询区 Dmitriy 在 ASP.net core 中使用gr
以下文章来源于公众号:DotNetCore实战
在 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 包裹所有的办法,太痛苦了。
我们可以给 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 集成越来越好,是得需要大家花费精力好好学习。
到此这篇关于在 asp.net Core 中为 gRPC 服务添加全局异常处理 的文章就介绍到这了,更多相关在 ASP.net Core 中为 gRPC 服务添加异常处理 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 在 ASP.NET Core 中为 gRPC 服务添加全局异常处理
本文链接: https://www.lsjlt.com/news/161849.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2023-05-21
2023-05-21
2023-05-21
2023-05-21
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0