[Workaround & Headache Prevention] Successfully create teams channel notification subscription with Microsoft Graph .NET Client Library v5

As part of the upgrade of the Microsoft Graph .NET Client Library from version 4 to version 5, my work mate and I have adapted the usage of the GraphServiceClient methods in context of teams channel notification subscription creation according to the official documentation. Unfortunately it didn’t work… and it cost us a few hours and above all nerves… In the meantime we finally found a solution which I gladly share with you to save you the same headache.

With Microsoft Graph .NET Client Library v4 the code looked as follows.

var subscription = new Subscription
{
	ChangeType = "created",
	NotificationUrl = notificationUrl,
	Resource = $"teams/{space.TeamsId}/channels/{space.GeneralChannelId}/messages",
	ExpirationDateTime = expirationDateTime, // max 2h!
	ClientState = space.SubscriptionSecret,
	LatestSupportedTlsVersion = "v1_2"
};

var response = await _graphClient
	.Subscriptions
	.Request(new[] { new QueryOption("model", "B") })
	.AddAsync(subscription);

According to the docs (see here), the updated code with Microsoft Graph .NET Client Library v5 would look as follows.

var subscription = new Subscription
{
	ChangeType = "created",
	NotificationUrl = notificationUrl,
	Resource = $"teams/{space.TeamsId}/channels/{space.GeneralChannelId}/messages?model=B",
	ExpirationDateTime = expirationDateTime, // max 2h!
	ClientState = space.SubscriptionSecret,
	LatestSupportedTlsVersion = "v1_2"
};

var response = await _graphClient
	.Subscriptions
    .PostAsync(subscription);

However as already mentioned above, this code did/does not work. It fails with the following exception message.

Fails with: [Status Code: BadRequest; Reason: Query parameter 'model' is not supported for this resource type.

After a lot of debugging, analysis and research we finally could make it work!

Working version inspired by https://stackoverflow.com/a/77451153/2796003 looks as follows

var subscription = new Subscription
{
	ChangeType = "created",
	NotificationUrl = notificationUrl,
	Resource = $"teams/{space.TeamsId}/channels/{space.GeneralChannelId}/messages",
	ExpirationDateTime = expirationDateTime, // max 2h!
	ClientState = space.SubscriptionSecret,
	LatestSupportedTlsVersion = "v1_2"
};

var requestInformation = _graphClient
	.Subscriptions
	.ToPostRequestInformation(subscription);
requestInformation.QueryParameters["model"] = new[] { "B" };
requestInformation.UrlTemplate += "{?model}";
var response =
	await _graphClient.RequestAdapter.SendAsync(
		requestInformation,
		Subscription.CreateFromDiscriminatorValue
	);

Seems to be a known issue that query parameters do not work as expected in POST requests using Microsoft Graph .NET Client Library v5 based on https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/1975.

Leave a comment

Website Powered by WordPress.com.

Up ↑