using Common.Utils; using CommonDomain; using CommonService; using Microsoft.AspNetCore.SignalR; namespace ChessGameHost.Middleware { public class HubExceptionFilter : IHubFilter { private readonly ILogger _logger; private readonly IApiLogService _apiLogService; public HubExceptionFilter(ILogger logger, IApiLogService apiLogService) { _logger = logger; _apiLogService = apiLogService; } public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) { if (invocationContext.HubMethodName == "SyncGameData") return await next(invocationContext); var apilog = new ApiLog() { requestTime = DateTime.Now, accessToken = "", clientIP = invocationContext.Context.ConnectionId, consumeTime = 0, requestHead = null, requestUrl = invocationContext.HubMethodName, requestMethod = "Socket", requestQuery = null, requestBody = invocationContext.HubMethodArguments.ToJson(), httpStatus = 200, responseBody = null, userAgent = null, device = null, deviceId = null, ip = null, source = null, version = null, sign = null }; try { await _apiLogService.InsertOneAsync(apilog); return await next(invocationContext); } catch (Exception e) { apilog.httpStatus = 500; apilog.responseBody = e.Message; await _apiLogService.InsertOneAsync(apilog); _logger.LogError(e, "HubExceptionMiddleware捕获异常"); return null; } } } }