CloudEventsMiddleware writes unexpected event data
- Dominant language
- C#
- Stars
- 1.2k
- Forks
- 378
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 5
Description
I have been having problems with receiving CloudEvents in my application. The event data I receive is encoded like this:
> "{\u0022id\u0022:\u002259f3323b-3290-40d8-9817-951cef726463\u0022,\u0022foo\u0022:\u0022bar\u0022}"
I debugged the [CloudEventsMiddleware](https://github.com/dapr/dotnet-sdk/blob/master/src/Dapr.AspNetCore/CloudEventsMiddleware.cs) and found the following:
My event looks something like this:
```json
{
"data": "{\"id\":\"e96330f4-1bd3-4c4d-bae5-4c71cf548458\",\"foo\":\"bar\"}",
"datacontenttype": "application/json",
"id": "99883fa1-7cc2-4bd8-a8cf-011508688563",
"pubsubname": "pub-sub",
"source": "some-app",
"specversion": "1.0",
"time": "2022-11-29T16:11:19+01:00",
"topic": "some-topic",
"traceid": "00-7c5b7wd01eb120d50b8299f67f1047bb-2118100363a603da-01",
"traceparent": "00-7w5b7ed01eb120d50b8299f67f1047bb-2118100363a603da-01",
"tracestate": "",
"type": "com.dapr.event.sent"
}
```
The middleware correctly assumes we're dealing with JSON here and jumps to [line 106 ](https://github.com/dapr/dotnet-sdk/blob/master/src/Dapr.AspNetCore/CloudEventsMiddleware.cs#L106)to call await JsonSerializer.SerializeAsync(body, data); which seems to be the troublemaker here. I'm not too familiar with System.Text.Json as we're still stuck on Newtonsoft but the outcome seems logical: We take an already valid JSON string and serialize it again. Is this expected behavior? Middleware down the line that needs to work on the body needs to deserialize twice, once to a JSON string and again to the actual object which seems counterintuitive.
Consider the case where isJson is false:
```csharp
else
{
//Rehydrate body from contents of the string
var text = data.GetString();
using var writer = new HttpResponseStreamWriter(body, Encoding.UTF8);
writer.Write(text);
}
```
Shouldn't this be the default behavior for JSON payloads?
Contributor guide
Assessment
This issue has not been assessed yet.