-
Notifications
You must be signed in to change notification settings - Fork 79
Description
Description
MockResponsePlugin attempts to parse request bodies as JSON even when the request uses the application/x-www-form-urlencoded content-type. This results in a warning:
MockResponsePlugin: Failed to parse request body as JSON. Placeholders in the mock response won't be replaced.
The plugin should only attempt to parse bodies as JSON when the content-type is a known JSON type or is absent (for backward compatibility).
Root Cause
The issue is in the [ReplacePlaceholders method in MockResponsePlugin.cs](https://github.com/dotnet/dev-proxy/blob/33a7bc4a7807f4a56ee847e3b12e4756dac6414a/DevProxy. Plugins/Mocking/MockResponsePlugin.cs#L528-L550). It unconditionally attempts to deserialize the request body as JSON without checking the Content-Type header first:
try
{
var requestBody = JsonSerializer. Deserialize<JsonElement>(request.BodyString, ProxyUtils.JsonSerializerOptions);
response.Body = ReplacePlaceholdersInObject(response. Body, requestBody, logger);
}
catch (Exception ex)
{
logger.LogDebug(ex, "Failed to parse request body as JSON");
logger.LogWarning("Failed to parse request body as JSON. Placeholders in the mock response won't be replaced.");
}Suggested Fix
Before attempting JSON parsing, check the request's Content-Type header. Only parse JSON if:
- The content-type is a JSON type (e.g.,
application/json,application/vnd.api+json, etc.) - No content-type is set (for backwards compatibility)
Expected behaviour
The plugin should only parse the request body as JSON if the content-type indicates a JSON type or if there is no content-type header. There should be no parsing attempts (and thus no warnings) for other content-types such as application/x-www-form-urlencoded.
Actual behaviour
When the content-type is set to application/x-www-form-urlencoded, MockResponsePlugin still attempts to parse the body as JSON and emits a warning that it failed to parse. This is both noisy and misleading for users sending form-encoded requests.
Steps to reproduce
-
Start Dev Proxy.
-
Send a POST request with content-type set to
application/x-www-form-urlencoded:curl -ikx http://127.0.0.1:8000 -X POST https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Messages. json \ -d 'To=+15559876543' \ -d 'From=+15551234567' \ -d 'Body=Hello from Dev Proxy! ' -
Observe the warning in the proxy logs:
MockResponsePlugin: Failed to parse request body as JSON. Placeholders in the mock response won't be replaced.
Dev Proxy Version
latest from main
Operating system (environment)
macOS
Shell
zsh
Configuration file
n/a
Additional Info
The warning should only appear when the content-type is JSON or unset, not for non-JSON content-types. This change will prevent unnecessary log noise and clarify actual parsing failures.