public static async Task SendMessage <TResponse>(HttpApiServerCallContext serverCallContext, JsonSerializerOptions serializerOptions, TResponse message) where TResponse : class { var response = serverCallContext.HttpContext.Response; try { GrpcServerLog.SendingMessage(serverCallContext.Logger); object responseBody; Type responseType; if (serverCallContext.DescriptorInfo.ResponseBodyDescriptor != null) { // TODO: Support recursive response body? responseBody = serverCallContext.DescriptorInfo.ResponseBodyDescriptor.Accessor.GetValue((IMessage)message); responseType = JsonConverterHelper.GetFieldType(serverCallContext.DescriptorInfo.ResponseBodyDescriptor); } else { responseBody = message; responseType = message.GetType(); } await JsonRequestHelpers.WriteResponseMessage(response, serverCallContext.RequestEncoding, responseBody, serializerOptions); GrpcServerLog.SerializedMessage(serverCallContext.Logger, responseType); GrpcServerLog.MessageSent(serverCallContext.Logger); } catch (Exception ex) { GrpcServerLog.ErrorSendingMessage(serverCallContext.Logger, ex); throw; } }
internal async Task ProcessHandlerErrorAsync(Exception ex, string method, bool isStreaming, JsonSerializerOptions options) { Status status; if (ex is RpcException rpcException) { // RpcException is thrown by client code to modify the status returned from the server. // Log the status and detail. Don't log the exception to reduce log verbosity. GrpcServerLog.RpcConnectionError(Logger, rpcException.StatusCode, rpcException.Status.Detail); status = rpcException.Status; } else { GrpcServerLog.ErrorExecutingServiceMethod(Logger, method, ex); var message = ErrorMessageHelper.BuildErrorMessage("Exception was thrown by handler.", ex, Options.EnableDetailedErrors); // Note that the exception given to status won't be returned to the client. // It is still useful to set in case an interceptor accesses the status on the server. status = new Status(StatusCode.Unknown, message, ex); } await JsonRequestHelpers.SendErrorResponse(HttpContext.Response, RequestEncoding, status, options); if (isStreaming) { await HttpContext.Response.Body.WriteAsync(GrpcProtocolConstants.StreamingDelimiter); } }
public HttpApiServerCallContext(HttpContext httpContext, MethodOptions options, IMethod method, CallHandlerDescriptorInfo descriptorInfo, ILogger logger) { HttpContext = httpContext; Options = options; _method = method; DescriptorInfo = descriptorInfo; Logger = logger; IsJsonRequestContent = JsonRequestHelpers.HasJsonContentType(httpContext.Request, out var charset); RequestEncoding = JsonRequestHelpers.GetEncodingFromCharset(charset) ?? Encoding.UTF8; // Add the HttpContext to UserState so GetHttpContext() continues to work HttpContext.Items["__HttpContext"] = httpContext; }