Skip to content

Commit 26d7a9b

Browse files
committed
Modernize ASP.NET Core samples
Signed-off-by: Erwin <erwinkramer@hotmail.com>
1 parent 8e86a0a commit 26d7a9b

13 files changed

Lines changed: 221 additions & 185 deletions

.vscode/launch.json

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
{
2-
// Use IntelliSense to find out which attributes exist for C# debugging
3-
// Use hover for the description of the existing attributes
4-
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
5-
"version": "0.2.0",
6-
"configurations": [
2+
// Use IntelliSense to find out which attributes exist for C# debugging
3+
// Use hover for the description of the existing attributes
4+
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "ASP.NET Core Sample Launch",
9+
"type": "dotnet",
10+
"request": "launch",
11+
"projectPath": "${workspaceFolder}/samples/CloudNative.CloudEvents.AspNetCoreSample/CloudNative.CloudEvents.AspNetCoreSample.csproj"
12+
},
713
{
814
"name": ".NET Core Launch (console)",
915
"type": "coreclr",
@@ -24,5 +30,5 @@
2430
"request": "attach",
2531
"processId": "${command:pickProcess}"
2632
}
27-
,]
33+
]
2834
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright (c) Cloud Native Foundation.
2+
// Licensed under the Apache 2.0 license.
3+
// See LICENSE file in the project root for full license information.
4+
5+
using CloudNative.CloudEvents.AspNetCore;
6+
using CloudNative.CloudEvents.Core;
7+
using CloudNative.CloudEvents.SystemTextJson;
8+
using Microsoft.AspNetCore.Http;
9+
using Microsoft.AspNetCore.Http.HttpResults;
10+
using Microsoft.Extensions.DependencyInjection;
11+
using System.Reflection;
12+
using System.Threading.Tasks;
13+
14+
namespace CloudNative.CloudEvents.AspNetCoreSample;
15+
16+
public class CloudEventBinding : IBindableFromHttpContext<CloudEventBinding>
17+
{
18+
public CloudEvent Value { get; init; }
19+
20+
public ProblemHttpResult Error { get; init; }
21+
22+
public static async ValueTask<CloudEventBinding> BindAsync(HttpContext context, ParameterInfo parameter)
23+
{
24+
Validation.CheckNotNull(context, nameof(context));
25+
Validation.CheckNotNull(parameter, nameof(parameter));
26+
27+
var request = context.Request;
28+
29+
// Even though we're not allowing non-JSON content in this binding,
30+
// types such as "text/xml" could still be parsed with the current JsonEventFormatter,
31+
// but it's just not making it strongly typed, or anything structured (XmlNode).
32+
// Depending on your use-case, it may or may not be desirable to allow that.
33+
if (request.ContentLength != 0 && !request.HasJsonContentType())
34+
{
35+
return new CloudEventBinding
36+
{
37+
Error = TypedResults.Problem(
38+
statusCode: StatusCodes.Status415UnsupportedMediaType,
39+
title: "Unsupported media type",
40+
detail: "Request content type is not JSON and not fully supported in this binding. " +
41+
"Please note: the CloudEvents specification does allow for any data content, " +
42+
"as long as it adheres to the provided datacontenttype."
43+
)
44+
};
45+
}
46+
47+
var formatter = context.RequestServices.GetRequiredService<JsonEventFormatter>();
48+
49+
var cloudEvent = await request.ToCloudEventAsync(formatter);
50+
51+
return new CloudEventBinding
52+
{
53+
Value = cloudEvent
54+
};
55+
}
56+
}

samples/CloudNative.CloudEvents.AspNetCoreSample/CloudEventJsonInputFormatter.cs

Lines changed: 0 additions & 63 deletions
This file was deleted.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright (c) Cloud Native Foundation.
2+
// Licensed under the Apache 2.0 license.
3+
// See LICENSE file in the project root for full license information.
4+
5+
using CloudNative.CloudEvents.AspNetCore;
6+
using CloudNative.CloudEvents.SystemTextJson;
7+
using Microsoft.AspNetCore.Http;
8+
using Microsoft.AspNetCore.Http.HttpResults;
9+
using System;
10+
using System.Linq;
11+
using System.Threading.Tasks;
12+
13+
namespace CloudNative.CloudEvents.AspNetCoreSample;
14+
15+
public static class CloudEventOperations
16+
{
17+
public static async Task<Results<ProblemHttpResult, JsonHttpResult<object>>> ReceiveCloudEvent(CloudEventBinding cloudEventBinding)
18+
{
19+
if (cloudEventBinding.Error is not null)
20+
{
21+
return cloudEventBinding.Error;
22+
}
23+
24+
var cloudEvent = cloudEventBinding.Value;
25+
26+
var cloudEventAttributes = cloudEvent.GetPopulatedAttributes()
27+
.ToDictionary(pair => pair.Key.Name, pair => pair.Key.Format(pair.Value));
28+
29+
return TypedResults.Json<object>(new
30+
{
31+
note = "wow, such event, much disassembling, very skill",
32+
cloudEvent.SpecVersion.VersionId,
33+
cloudEventAttributes,
34+
cloudEvent.Data
35+
});
36+
}
37+
38+
/// <summary>
39+
/// Generates a CloudEvent.
40+
/// </summary>
41+
public static async Task GenerateCloudEvent(HttpResponse response, JsonEventFormatter formatter, ContentMode contentMode = ContentMode.Structured)
42+
{
43+
var evt = new CloudEvent
44+
{
45+
Type = "CloudNative.CloudEvents.AspNetCoreSample",
46+
Source = new Uri("https://github.com/cloudevents/sdk-csharp"),
47+
Time = DateTimeOffset.Now,
48+
DataContentType = "application/json",
49+
Id = Guid.NewGuid().ToString(),
50+
Data = new
51+
{
52+
Language = "C#",
53+
EnvironmentVersion = Environment.Version.ToString()
54+
}
55+
};
56+
57+
response.StatusCode = StatusCodes.Status200OK;
58+
await evt.CopyToHttpResponseAsync(response, contentMode, formatter);
59+
}
60+
}

samples/CloudNative.CloudEvents.AspNetCoreSample/CloudNative.CloudEvents.AspNetCoreSample.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<ItemGroup>
88
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.AspNetCore\CloudNative.CloudEvents.AspNetCore.csproj" />
99
<ProjectReference Include="..\..\src\CloudNative.CloudEvents\CloudNative.CloudEvents.csproj" />
10-
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.NewtonsoftJson\CloudNative.CloudEvents.NewtonsoftJson.csproj" />
10+
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.SystemTextJson\CloudNative.CloudEvents.SystemTextJson.csproj" />
1111
</ItemGroup>
1212

1313
</Project>
Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,56 @@
11
@HostAddress = https://localhost:5001
22

3+
### Send via Structured mode
4+
5+
POST {{HostAddress}}/api/events/receive
6+
Content-Type: application/cloudevents+json; charset=utf-8
7+
8+
{
9+
"specversion": "1.0",
10+
"type": "com.example.myevent",
11+
"source": "urn:example-com:mysource:abc",
12+
"id": "{{$guid}}",
13+
"data": {
14+
"message": "Hello world!"
15+
}
16+
}
17+
18+
### Send via Binary mode
19+
320
POST {{HostAddress}}/api/events/receive
421
Content-Type: application/json
522
CE-SpecVersion: 1.0
623
CE-Type: "com.example.myevent"
724
CE-Source: "urn:example-com:mysource:abc"
8-
CE-Id: "c457b7c5-c038-4be9-98b9-938cb64a4fbf"
25+
CE-Id: "{{$guid}}"
926

1027
{
1128
"message": "Hello world!"
1229
}
1330

14-
###
31+
### Send content-less via Binary mode
32+
33+
POST {{HostAddress}}/api/events/receive
34+
CE-SpecVersion: 1.0
35+
CE-Type: "com.example.myevent"
36+
CE-Source: "urn:example-com:mysource:abc"
37+
CE-Id: "{{$guid}}"
38+
39+
### Send unsupported media type (XML) via Binary mode
40+
41+
POST {{HostAddress}}/api/events/receive
42+
Content-Type: text/xml
43+
CE-SpecVersion: 1.0
44+
CE-Type: "com.example.myevent"
45+
CE-Source: "urn:example-com:mysource:abc"
46+
CE-Id: "{{$guid}}"
47+
48+
<message>Hello world!</message>
49+
50+
### Generate via Structured mode
1551

1652
GET {{HostAddress}}/api/events/generate
53+
54+
### Generate via Binary mode
55+
56+
GET {{HostAddress}}/api/events/generate?contentMode=Binary

samples/CloudNative.CloudEvents.AspNetCoreSample/Controllers/CloudEventController.cs

Lines changed: 0 additions & 66 deletions
This file was deleted.

samples/CloudNative.CloudEvents.AspNetCoreSample/Program.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,21 @@
33
// See LICENSE file in the project root for full license information.
44

55
using CloudNative.CloudEvents.AspNetCoreSample;
6+
using CloudNative.CloudEvents.SystemTextJson;
67
using Microsoft.AspNetCore.Builder;
7-
using CloudNative.CloudEvents.NewtonsoftJson;
88
using Microsoft.Extensions.DependencyInjection;
9+
using System.Text.Json;
910

1011
var builder = WebApplication.CreateBuilder(args);
1112

12-
builder.Services.AddControllers(opts =>
13-
opts.InputFormatters.Insert(0, new CloudEventJsonInputFormatter(new JsonEventFormatter())));
13+
JsonSerializerOptions jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
14+
builder.Services.AddSingleton(new JsonEventFormatter(jsonOptions, new JsonDocumentOptions()));
1415

1516
var app = builder.Build();
1617

17-
app.MapControllers();
18+
var apiEvents = app.MapGroup("/api/events");
19+
apiEvents.MapPost("/receive", CloudEventOperations.ReceiveCloudEvent);
20+
apiEvents.MapGet("/generate", CloudEventOperations.GenerateCloudEvent);
1821

1922
app.Run();
2023

samples/HttpSend/HttpSend.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
<ItemGroup>
99
<PackageReference Include="McMaster.Extensions.CommandLineUtils" />
1010
<ProjectReference Include="..\..\src\CloudNative.CloudEvents\CloudNative.CloudEvents.csproj" />
11-
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.NewtonsoftJson\CloudNative.CloudEvents.NewtonsoftJson.csproj" />
11+
<ProjectReference Include="..\..\src\CloudNative.CloudEvents.SystemTextJson\CloudNative.CloudEvents.SystemTextJson.csproj" />
1212
</ItemGroup>
1313

1414
</Project>

0 commit comments

Comments
 (0)