diff --git a/servlet-core/src/main/java/io/micronaut/servlet/http/ServletHttpHandler.java b/servlet-core/src/main/java/io/micronaut/servlet/http/ServletHttpHandler.java index 9f055eef8..469ed4475 100644 --- a/servlet-core/src/main/java/io/micronaut/servlet/http/ServletHttpHandler.java +++ b/servlet-core/src/main/java/io/micronaut/servlet/http/ServletHttpHandler.java @@ -26,6 +26,7 @@ import io.micronaut.core.execution.ExecutionFlow; import io.micronaut.core.io.Writable; import io.micronaut.core.propagation.PropagatedContext; +import io.micronaut.core.reflect.ClassUtils; import io.micronaut.core.type.Argument; import io.micronaut.core.util.ArrayUtils; import io.micronaut.http.HttpAttributes; @@ -380,7 +381,7 @@ private void encodeResponse(ServletExchange exchange, if (body != null && !isVoid) { Class bodyType = body.getClass(); - if (bodyArgument == null || !bodyArgument.isInstance(body)) { + if (bodyArgument == null || !bodyArgument.isInstance(body) || bodyArgument.getType().equals(Object.class)) { bodyArgument = (Argument) Argument.of(bodyType); } ServletResponseEncoder responseEncoder = (ServletResponseEncoder) responseEncoders.get(bodyType); @@ -421,7 +422,15 @@ private void encodeResponse(ServletExchange exchange, if (!(body instanceof HttpStatus)) { messageBodyWriter = routeInfoAttribute.map(RouteInfo::getMessageBodyWriter).orElse(null); if (messageBodyWriter == null) { - messageBodyWriter = new DynamicMessageBodyWriter(messageBodyHandlerRegistry, List.of(mediaType)); + MediaType finalMediaType = mediaType; + Argument finalBodyArgument = bodyArgument; + Optional> writer = messageBodyHandlerRegistry.findWriter(bodyArgument, List.of(mediaType)); + if (writer.isEmpty() && mediaType.equals(MediaType.TEXT_PLAIN_TYPE) && ClassUtils.isJavaBasicType(body.getClass())) { + // TODO: remove after Core 4.6 + writer = (Optional) messageBodyHandlerRegistry.findWriter(Argument.STRING, List.of(MediaType.TEXT_PLAIN_TYPE)); + } + messageBodyWriter = writer + .orElseThrow(() -> new CodecException("Cannot encode value of argument [" + finalBodyArgument + "]. No possible encoders found for media type: " + finalMediaType)); } }